简体   繁体   中英

Reading a C file line by line where each line has an unknown length

I am writing a program in C that opens a file and reads in the file line by line performing various actions with each string after it reads in the line.

Now my issue is that I have a loop set up so I read one line in and do the necessary things to that line and then move to the next one until the end of the file. The problem I am having is that I know the maximum line length is 80 characters but it can be less than this so I am having a lot of trouble stopping at the end of the line in order to properly perform the necessary actions.

I would attach code but I am stumped at this part and it is so early that I don't really know if my code would help as it is just at the reading stage. I am unable to figure out how to read in a line when it's length is unknown. Any help would be greatly appreciated!

Define a char buffer with a size at least 82 (80 chars + linefeed + null byte).

In a loop, repeatedly call fgets(buffer, sizeof buffer, file) to read one line and perform the tasks until you reach the end of file:

char buffer[82];

while (fgets(buffer, sizeof buffer, file)) {
    /* handle the line in buffer */
    ...
}

caution: buffer contains a '\\n' as the last character.

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