我正在尝试扫描文本文件并将字符输入到数组中。
char newArray[500];
FILE *fp2;
fp2 = fopen("LeftPattern_Color.txt", "r");
char ch;
while ((ch = fgetc(fp2)) != EOF)
{
int i = 0;
newArray[i] = ch;
i++;
}
fclose(fp2);
但是当我打印出字符以测试输入的字符是否在newArray[500]
中时,没有打印任何内容。
for(int i = 0; i < 500; i++)
{
printf("%c", newArray[i]);
}
如备注中所述,您需要使用ch的int
才能与EOF
进行比较,并且int i = 0;
必须在您总是用newArray[0]
编写的其他for
之外
另请注意,您编写数组的所有 500 个元素,即使您更正了代码,您也会打印非初始化元素,以防文件少于 500 个字符,您只需要写入从 0 到i不包含的元素
无论如何,您可以使用fread
size_n nread = fread(newArray, 1, sizeof(newArray), fp2);
要打印,您可以使用fwrite
:
fwrite(newArray, 1, nread, stdout);
我还鼓励您检查fp2不是 NULL 以检测您无法打开文件的情况
代码中的更正版本可以是:
#include <stdio.h>
int main()
{
FILE *fp2 = fopen("LeftPattern_Color.txt", "r");
if (fp2 == NULL)
perror("cannot read LeftPattern_Color.txt");
else {
char newArray[500];
int ch;
int i = 0;
while ((ch = fgetc(fp2)) != EOF)
newArray[i++] = ch;
fclose(fp2);
for(int i2 = 0; i2 < i; i2++)
printf("%c", newArray[i2]);
}
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall f.c
pi@raspberrypi:/tmp $ ./a.out
cannot read LeftPattern_Color.txt: No such file or directory
pi@raspberrypi:/tmp $ (date ; pwd) > LeftPattern_Color.txt
pi@raspberrypi:/tmp $ ./a.out
dimanche 17 mai 2020, 11:37:47 (UTC+0200)
/tmp
pi@raspberrypi:/tmp $
较短的版本可以是:
#include <stdio.h>
int main()
{
FILE *fp2 = fopen("LeftPattern_Color.txt", "r");
if (fp2 == NULL)
perror("cannot read LeftPattern_Color.txt");
else {
char newArray[500];
size_t nread = fread(newArray, 1, sizeof(newArray), fp2);
fclose(fp2);
fwrite(newArray, 1, nread, stdout);
}
return 0;
}
编译和删减:
pi@raspberrypi:/tmp $ gcc -Wall ff.c
pi@raspberrypi:/tmp $ rm LeftPattern_Color.txt
pi@raspberrypi:/tmp $ ./a.out
cannot read LeftPattern_Color.txt: No such file or directory
pi@raspberrypi:/tmp $ (date ; pwd) > LeftPattern_Color.txt
pi@raspberrypi:/tmp $ ./a.out
dimanche 17 mai 2020, 11:41:19 (UTC+0200)
/tmp
pi@raspberrypi:/tmp $