【发布时间】:2012-06-02 00:04:24
【问题描述】:
我编写了一个简单的 C 程序,它采用 .txt 文件并将所有空格替换为连字符。但是,程序进入了一个无限循环,结果是无穷无尽的连字符数组。
这是输入文件:
a b c d e f
这是进程崩溃后的文件:
a----------------------------------------------------------------------------
----------------------------------------... (continues thousands of times)...
我猜是fread()、fwrite()和fseek()的意外行为的原因,或者我对这些功能的误解。这是我的代码:
#include <stdlib.h>
#include <stdio.h>
#define MAXBUF 1024
int main(void) {
char buf[MAXBUF];
FILE *fp;
char c;
char hyph = '-';
printf("Enter file name:\n");
fgets(buf, MAXBUF, stdin);
sscanf(buf, "%s\n", buf); /* trick to replace '\n' with '\0' */
if ((fp = fopen(buf, "r+")) == NULL) {
perror("Error");
return EXIT_FAILURE;
}
fread(&c, 1, 1, fp);
while (c != EOF) {
if (c == ' ') {
fseek(fp, -1, SEEK_CUR); /* rewind file position indicator to the position of the ' ' */
fwrite(&hyph, 1, 1, fp); /* write '-' instead */
}
fread(&c, 1, 1, fp); /* read next character */
}
fclose(fp);
return EXIT_SUCCESS;
}
这里有什么问题?
【问题讨论】:
-
您使用的是什么操作系统?我编译并运行了你的程序,由于没有正确检查 EOF(如乔的回答中所述),它进入了一个无限循环,但是它不会创建一个无休止的连字符流。