简体   繁体   中英

How to read file more than once C

I am trying to store a list of words from a file into a char* . I am not to assume a max number of lines or a max number of characters. So to combat this, I decided to do a run through of the .txt file to find the number of lines and the maximum number of characters so I can allocate memory to char * list.

However, when I used GDB to debug my program, it skips over the second runthough of the file to store in the words. Why is it doing this and how do I fix it? Thanks!

void readFile(int argc, char** argv)
{
    FILE *myFile;
    char** list;
    char c;
    int wordLine = 0, counter = 0, i;
    int maxNumberOfChars = 0, numberOfLines = 0, numberOfChars = 0;

    myFile = fopen(argv[1], "r");

    if(!myFile)
    {
        printf("No such file or directory\n");
        exit(EXIT_FAILURE);  
    }

    while((c = fgetc(myFile)) !=EOF)
    {
        numberOfChars++;
        if(c == '\n')
        {
            if(maxNumberOfChars < numberOfChars)
                maxNumberOfChars += numberOfChars + 1;

            numberOfLines++;
        }
    }

    fseek(myFile, 0, SEEK_SET);

    list = malloc(sizeof(char*)*numberOfLines);

    for(i = 0; i < wordLine ; i++)
        list[i] = malloc(sizeof(char)*maxNumberOfChars);


    while((c = fgetc(myFile)) != EOF)
    {
        if(c == '\n' && counter > 0)
        {
            list[wordLine][counter] = '\0';
            wordLine++;
            counter = 0;
        }
        else if(c != '\n')
        {
            list[wordLine][counter] = c;
            counter++;
        }
    } 
    fclose(myFile);
}

You need to use fseek to reset the read-pointer of the file before your second loop.

Add something like this

fseek(myFile, 0, SEEK_SET);

or

rewind(myFile);

thanks to @ThomasPadron-McCarthy.

1st of all, your technique is bad because it is very slow. You can just allocate some memory and then use realloc if you need more.

2nd: you can use stat() on a file to know the size. You won't know the number of lines in it but it could be useful.

3rd: you can use fseek() to move the cursor back to the beginning of the file, and in general to any position within the file.

再次读取之前,请使用rewind(myFile)。

rewind(myFile)

but you don't need to read the whole file just to find out the number of chars. You can use this structure

struct stat file_stat;
fstat(file_id, &file_stat);
int size_to_read = file_stat.st_size - 1;

you don need to know the number of lines, because you can can use realloc on line:

list=realloc(list,(sizeof(char*)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM