【发布时间】:2014-11-02 09:07:07
【问题描述】:
我 3 天前刚开始学习 C,我正在尝试制作一个程序来接收文件,读取字符,并从中删除所有空格和制表符。我是一名初级程序员,在开始学习 C 之前只学了一点 MATLAB。我使用的是 Ubuntu 12.04。
这是我的代码:
#include <stdio.h>
int main ()
{
FILE * pFile;
FILE * pFile2;
int c;
pFile = fopen ("spaces.txt","r");
pFile2 = fopen ("nospaces.txt","w");
if (pFile==NULL) perror ("Error opening file");
else
{
while (c != EOF)
{
c = fgetc (pFile);
if (!(c == ' ' || c == ' '))
{
fputc (c, pFile2);
}
}
fclose (pFile2);
fclose (pFile);
}
return 0;
}
当我打开新文件“nospaces.txt”时,一切都很好,只是最后有一个奇怪的字符。 Gedit 说它是红色背景的 /FF 或 /00 并抱怨我不应该编辑该文件,因为我可能会损坏它。无论我试图做什么,我都无法在最后摆脱那个奇怪的角色。以下是我尝试过的示例:
-使用 fputc (EOF , pFile2) 在 pFile2 末尾添加 EOF、'\0' 和其他随机字符 - 对 c 的值施加随机约束,使其不会选择不是字母或数字的字符(如 40
请帮忙。 谢谢。
【问题讨论】:
-
while (c != EOF){ c = fgetc (pFile);-->while ((c = fgetc (pFile)) != EOF){