简体   繁体   English

逐行读取C文件,其中每行的长度未知

[英]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. 我正在用C编写一个程序,该程序打开一个文件,并逐行读取文件,并在读取该行后对每个字符串执行各种操作。

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. 我遇到的问题是,我知道最大行长为80个字符,但是可以小于此长度,因此为了正确执行必要的操作,我在行尾停止时遇到很多麻烦。

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). 定义一个大小至少为82(80个字符+换行符+空字节)的char缓冲区。

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: 在循环中,重复调用fgets(buffer, sizeof buffer, file)以读取一行并执行任务,直到到达文件末尾:

char buffer[82];

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

caution: buffer contains a '\\n' as the last character. 注意: buffer的最后一个字符为'\\n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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