Не печатать первые 5 символов файла

Цикл, который читает из файла и печатает результат, не печатает первые 5 символов из всех прочитанных файлов. Если я печатаю их по 1 символу за раз, это работает нормально, но я читаю числа с плавающей запятой из файла, который мне нужно обработать позже. Числа разделены пробелом, поэтому я пытаюсь печатать только при встрече с пробелами.

вот мой исходный код

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

#define BUFFER_SIZE 100
#define READ_END 0
#define WRITE_END 1

//main function
int main(int argc, char *argv[])
{
    //process ids
    int processIds[argc - 1];
    int pipes[argc - 1][2];
    char *fileNames[argc - 1];
    int status; 

    //check if at least one data file
    if (argc == 1)
    {
        return -1;
        //end program    
    }

    //get file names and store in array fileNames
    int i;
    for (i = 0; i < (argc - 1); i++)
    {
        fileNames[i] = argv[i + 1];
    }    

    //create child processes
    for (i = 0; i < (argc - 1); i++)
    {
        //make a pipe for communication
        if (pipe(pipes[i]))
        {
            printf("bad pipe");
            return -1;
        }
        //make a child process
        processIds[i] = fork();

        //check if child or paren process
        if (processIds[i] == 0)
        {
            //child process
            //close unused end

            close(pipes[i][READ_END]);

            //make file
            FILE *dataset = fopen(fileNames[i], "r");

            //test if file opened
            if (dataset == 0)
            {
                printf("could not find/open file");
                return -1;
            }

            //read and process file
            char *x;
            char *num = "";
            int min, max;
            while ((*x = fgetc(dataset)) != EOF)
            {
                if ((x == " ") || (x == "\t") || (x == "\n"))
                {
                    //end of number
                    printf("A%s B%s", num, num);
                    num = "";
                }
                else
                {
                    strcat(num, x);
                }
                //printf("%c", x);    
            }
            printf("\n\n");
            char msg[BUFFER_SIZE];

            write(pipes[i][WRITE_END], msg, strlen(msg) + 1);
            fclose(dataset);
            exit(0);
        }
        else if (processIds[i] < 0)
        {
            //error
            return -1;    
        }
        else
        {
            //parent process closes write end of pipe
            close(pipes[i][WRITE_END]);
        }
    }

    //wait for children
    for (i = 0; i < (argc - 1); i++)
    {
        //create a read buffer
        char read_buf[BUFFER_SIZE];

        //wait and get pid of completed child
        int pid = wait(&status);

        //find which child completed
        int j = 0;
        while (pid != processIds[j] && j < (argc - 1))
        {
            //pid not recognized, should not happen
            if (j >= (argc - 1))
            {
                printf("bad pid");
                return -1;
            }
            j++;
        }
        //read from completed child
        read(pipes[j][READ_END], read_buf, BUFFER_SIZE);
    }

    return 0;
}

1 ответ

Я могу заметить следующие ошибки, касающиеся вашего кода:

1) Распределение памяти

вам нужно выделить свой num переменная

пример:

char *num = malloc(10);

2) возвращаемый тип

'fgetc' не возвращает ни указатель, ни символ, поэтому вы должны определить

int x;

x = fgetc(dataset);

3) ваше состояние не так

if ((x == ' ') || (x == '\t') || (x == '\n'))

Обратите внимание, что ' ' не является " "


СЕЙЧАС, как мое предложение прочитать эти отдельные строки:

1) прочитать весь файл в буфере:

char buff[SIZE];
dataset= fopen("fileName.txt", "r");
   if( dataset!= NULL ){
      while ( !feof(fp ) ){
         memset(buff, '\0', sizeof( buff) );
         fgets(buff, SIZE, (FILE*)dataset);
      }
      fclose(dataset);
   }

2) использовать strchr найти следующий space и распечатать свои строки см. пример использования здесь

Другие вопросы по тегам