使用新行分隔符遍历文件的最佳方法
Best way to iterate through a file with new line separators
假设我想读取一个文件,其中每一行都有一个字符串,当有新行或文件末尾时,我打印读取的字符数。例如,
abcdf
asd
sdfsd
aa
这将打印(计算每个字符串末尾的换行符):
10
8
(最后一行末尾没有新行,所以我们得到 8 而不是 9)。我可以做这样的事情
FILE* f;
// ...
int charCount = 0;
char line[20];
while (fgets(line, sizeof line, f))
{
if (strcmp(line, "\n") == 0)
{
printf("%d\n", charCount);
charCount = 0;
}
else
{
charCount += strlen(line);
}
}
printf("%d\n", charCount);
注意我必须在循环结束后重复 printf,因为如果我不这样做,我就不会打印最后一个值(因为文件到达末尾并且末尾没有新行).对于printf
,这还不错,但是如果我有更复杂的东西,就会导致很多重复的代码。我的解决方法是将我想要的东西放在一个函数中,然后在循环之后调用该函数,但我觉得必须有更好的方法。有没有更好的方法来解析这样的文件?最好不要逐个字符,以防我有一些需要使用 fscanf
with.
的格式化数据
您可以将 fgets
调用移动到 while
循环的主体中,同时在循环条件和打印条件中检查其结果。它应该在循环到非 NULL 值之前正确初始化。
FILE* f;
// ...
int charCount = 0;
char line[20];
char *result = line;
while (result)
{
result = fgets(line, sizeof line, f);
if ( result == NULL || strcmp(line, "\n") == 0 )
{
printf("%d\n", charCount);
charCount = 0;
}
else
{
charCount += strlen(line);
}
}
你可以用穴居人的方式来做...
char ch;
int i = 0;
FILE *fp = fopen("yourfile.txt", "r");
while (feof(fp) == 0)
{
i++;
if ((ch = fgetc(fp)) == '\n')
printf("%d\n", --i), i = 0;
}
if (i > 1) printf("%d\n", --i);
fclose(fp);
假设我想读取一个文件,其中每一行都有一个字符串,当有新行或文件末尾时,我打印读取的字符数。例如,
abcdf
asd
sdfsd
aa
这将打印(计算每个字符串末尾的换行符):
10
8
(最后一行末尾没有新行,所以我们得到 8 而不是 9)。我可以做这样的事情
FILE* f;
// ...
int charCount = 0;
char line[20];
while (fgets(line, sizeof line, f))
{
if (strcmp(line, "\n") == 0)
{
printf("%d\n", charCount);
charCount = 0;
}
else
{
charCount += strlen(line);
}
}
printf("%d\n", charCount);
注意我必须在循环结束后重复 printf,因为如果我不这样做,我就不会打印最后一个值(因为文件到达末尾并且末尾没有新行).对于printf
,这还不错,但是如果我有更复杂的东西,就会导致很多重复的代码。我的解决方法是将我想要的东西放在一个函数中,然后在循环之后调用该函数,但我觉得必须有更好的方法。有没有更好的方法来解析这样的文件?最好不要逐个字符,以防我有一些需要使用 fscanf
with.
您可以将 fgets
调用移动到 while
循环的主体中,同时在循环条件和打印条件中检查其结果。它应该在循环到非 NULL 值之前正确初始化。
FILE* f;
// ...
int charCount = 0;
char line[20];
char *result = line;
while (result)
{
result = fgets(line, sizeof line, f);
if ( result == NULL || strcmp(line, "\n") == 0 )
{
printf("%d\n", charCount);
charCount = 0;
}
else
{
charCount += strlen(line);
}
}
你可以用穴居人的方式来做...
char ch;
int i = 0;
FILE *fp = fopen("yourfile.txt", "r");
while (feof(fp) == 0)
{
i++;
if ((ch = fgetc(fp)) == '\n')
printf("%d\n", --i), i = 0;
}
if (i > 1) printf("%d\n", --i);
fclose(fp);