[英]Loop Problem while reading a text file in C
Hi guys i wanna read a text file word by word and count the words while doing it and then pass the words and numbers to my linked list.嗨,伙计们,我想逐字阅读文本文件并在执行此操作时计算单词,然后将单词和数字传递给我的链接列表。
But i have a loop problem.但我有一个循环问题。 I can't escape from the infinite loop.我无法摆脱无限循环。
Here is my code:这是我的代码:
int main()
{
char kelime[100];
char kelime2[100];
long a = 0;
FILE * dosya = fopen("oku.txt", "r");
while(1)
{
fseek(dosya,a,SEEK_CUR);
if(feof(dosya))
{
break;
}
while(fscanf(dosya, "%99[^ \n]", kelime) == 1)
{
printf("%s \n",kelime);
a = ftell(dosya);
}
while(1)
{
fscanf(dosya, "%s" , kelime2);
printf("%s \n",kelime2);
if((strcmp(kelime, kelime2))== 0)
{
// Things to do...
}
memset(kelime2,0,sizeof(kelime2));
if(feof(dosya))
{
rewind(dosya);
break;
}
}
}
fclose(dosya);
return 0;
}
To read any kind of space-delimited word, all you need is something like:要阅读任何一种以空格分隔的单词,您只需要以下内容:
while (fscanf(dosya, "%99s", kelime) == 1)
{
// Do something with the "word" in kelime
}
The scanf
family of functions all return the number of conversions it successfully made. scanf
系列函数都返回它成功进行的转换次数。 With a single conversion specifier it can only return 1
on success, 0
if the specifier could not be matched (should never happen in this case) or -1
on error or end of file.使用单个转换说明符,它只能在成功时返回1
,如果说明符无法匹配(在这种情况下永远不会发生),则返回0
,或者在错误或文件结束时返回-1
。
The loop will simply read all words in the input file until the end of the file.循环将简单地读取输入文件中的所有单词,直到文件结束。
Putting it together in a program that reads and print all words, it would look something like this:把它放在一个读取和打印所有单词的程序中,它看起来像这样:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *dosya = fopen("oku.txt", "r");
if (dosya == NULL)
{
perror("Could not open file");
return EXIT_FAILURE;
}
char kelime[100];
size_t counter = 0;
while (fscanf(dosya, "%99s", kelime) == 1)
{
printf("Read word #%zu: %s\n", ++counter, kelime);
}
fclose(dosya);
printf("There was a total of %zu \"words\" in the file\n", counter);
}
A little explanation for the %zu
format specifier for printf
:对printf
的%zu
格式说明符的一点解释:
The u
is the base format (it's really %u
), and stands for u nsigned integer. u
是基本格式(实际上是%u
) ,代表无符号 integer。 The z
prefix tells printf
that the corresponding argument is really a size_t
value. z
前缀告诉printf
对应的参数实际上是一个size_t
值。
The type size_t
is a standard C type that is used for all kinds of sizes, counters and indexes. size_t
类型是标准的 C 类型,用于各种尺寸、计数器和索引。 It's an unsigned integer of unspecified size.这是一个未指定大小的未签名 integer。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.