【发布时间】:2015-04-27 15:10:05
【问题描述】:
我前段时间开始学习 C(通过 Youtube 和 K&R),我正在尝试编写一些程序作为练习。 目前我想创建一个从文件中读取单词并将其开头与用户输入进行比较的程序。 该程序成功地比较了第一个单词并给了我一个结果,但我就是无法让 fseek() 正确移动到下一行! (这是寻找词的部分的当前版本。)
fp= fopen("final.txt", "r");
for (i=0; i<8; i++){
fseek(fp, fileCount, SEEK_CUR);
fgets(strFile, 20, fp);
fileCount= strlen(strFile);
printf("Strlen %d. is: %d\n", i+1, fileCount);
printf("String is %s", strFile);
compareStr(strUser, strFile);
};
fclose(fp);
fileCount 设置为 0 并且 strlen() 应该返回字符串 srtFile 的长度,但它不是很好。我什至尝试手动设置 fseek() ,但它就是不动。 我文件中的单词是:First、Last、Index、Field、ID、Number、Fire、Film。 (每个都在一个新行中)。 当我运行程序并输入 F(以搜索具有大写字母 f 的单词)时,输出为:
Type in the letters: F
Strlen 1. is: 6
String is First
Match found: First
Strlen 2. is: 6
String is Index
Strlen 3. is: 1
String is
Strlen 4. is: 2
String is D
Strlen 5. is: 5
String is mber
Strlen 6. is: 1
String is
Strlen 7. is: 3
String is ilmStrlen 8. is: 3
String is ilm
Process returned 0 (0x0) execution time : 2.218 s
Press any key to continue.
我很绝望。有什么想法/线索吗?
[编辑] 非常感谢所有帮助我的人!
【问题讨论】:
-
你不想增加
fileCount吗?如果您在 Windows 中,由于 CRLF 约定,您可能希望使用“rb”打开。如果您按顺序阅读文件,为什么还要打扰fseek? -
你的文件指针已经在下一个单词处,fgets 在读取时移动文件指针,所以 fseek 是多余的。
-
BTW
fseek对于以文本模式打开的文件可能很危险;解释here。摘要:由于\n\r\n转换,fseek的参数应该为 0 或来自较早的ftell调用。所以你应该在你的程序中同时使用fseek和ftell(或者不使用?也许你根本不需要fseek?)。 -
在代码中调用系统函数 fopen、fseek、fgets 时应检查返回值以确保不会发生错误(和/或使代码能够识别错误事件并具有有机会修复它。
-
在发布的代码中,绝对不需要调用 fseek,因为调用将步进文件指针(在调用 fgets 之后,fgets 读取的字符数量已经向前移动)