有很多方法可以做到这一点。
简单的方法
一个简单的办法是循环的文字阅读:
f = fopen("words.txt","r"); // attention !! open in "r" mode !!
...
int rc;
do {
rc=fscanf(f, "%99s", string1); // attempt to read
} while (rc==1 && !feof(f)); // while it's successfull.
... // here string1 contains the last successfull string read
但是这需要一个字由空格分隔字符的任意组合。请注意使用scanf()
格式中的with,以确保不会发生缓冲区溢出。
rc=read_word(f, string1, 100);
:
更精确的方式
建立在以前的尝试,如果你想的话更严格的定义,你可以用自己的函数调用替换到的scanf()
该功能类似于:
int read_word(FILE *fp, char *s, int szmax) {
int started=0, c;
while ((c=fgetc(fp))!=EOF && szmax>1) {
if (isalpha(c)) { // copy only alphabetic chars to sring
started=1;
*s++=c;
szmax--;
}
else if (started) // first char after the alphabetics
break; // will end the word.
}
if (started)
*s=0; // if we have found a word, we end it.
return started;
}
可能是最好的方法,尤其是如果您的文件很大。如果你的“单词”比文件的末尾大,那么可能会发生麻烦。 –
是的,确切地说。搜索继续,直到找到该单词。 – fluter
好方法!但是,在文本模式下读取文件末尾是不可移植的:标准中写明“7.21.9.2:*对于文本流,任一偏移量应为零,或者偏移量应为先前成功调用函数返回的值函数在与同一个文件相关的数据流上,因此应该是SEEK_SET。*“ - 另见:http://www.cplusplus.com/reference/cstdio/fseek/ – Christophe