我写了一个简单的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;
}
这里的问题是什么?