为什么我的C程序不能工作?从文件中读取
我是C编程新手,我正在尝试制作一个程序来读取名为input的文件的上下文为什么我的C程序不能工作?从文件中读取,c,file,io,C,File,Io,我是C编程新手,我正在尝试制作一个程序来读取名为input的文件的上下文 #include <stdio.h> #include <stdlib.h> int main() { char ch; FILE *in; in = fopen("input","r"); printf("The contents of the file are\n"); fscanf(in,"%c",&ch); printf("%c",c
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *in;
in = fopen("input","r");
printf("The contents of the file are\n");
fscanf(in,"%c",&ch);
printf("%c",ch);
fclose(in);
return 0;
}
#包括
#包括
int main()
{
char ch;
文件*in;
in=fopen(“输入”、“r”);
printf(“文件的内容是\n”);
fscanf(在、%c、&ch中);
printf(“%c”,ch);
fclose(in);
返回0;
}
试试这个-
char text[100];
fp=fopen(name,"r");
fgets(text,sizeof(text),fp); //99 is maximum number of characters to be printed including newline, if it exists
printf("%s\n",text);
fclose(fp);
您的代码只读取文件的第一个字符。没有循环可以读取整个文件。这是你的本意吗 另外,检查文件打开是否成功。输入文件名是否为“input”?您应该使用:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *in;
/*Don't forget the extension (.txt)*/
if(in = fopen("input.txt","r") == NULL);
{
printf("File could not be opened\n");
}
else
{
printf("The contents of the file are\n");
/*I assume that you are reading char types*/
fscanf(in,"%c",&ch);
/*Check end-of-file indicator*/
while(!feof(in))
{
printf("%c",ch);
fscanf(in,"%c",&ch);
}
}
fclose(in);
return 0;
}
#包括
#包括
int main()
{
char ch;
文件*in;
/*不要忘记扩展名(.txt)*/
如果(in=fopen(“input.txt”,“r”)==NULL);
{
printf(“无法打开文件\n”);
}
其他的
{
printf(“文件的内容是\n”);
/*我假设您正在读取字符类型*/
fscanf(在、%c、&ch中);
/*检查文件结束指示器*/
而(!feof(in))
{
printf(“%c”,ch);
fscanf(在、%c、&ch中);
}
}
fclose(in);
返回0;
}
您应该记住验证文件是否打开,这始终是一种良好的做法。假设文件
输入的内容为:
Hello World
您可以尝试以下代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
FILE *in;
in = fopen("input","r");
printf("The contents of the file are\n");
while(fscanf(in, "%c", &ch) != EOF)
{
printf("%c",ch);
}
fclose(in);
return 0;
}
请描述input
文件的内容,以及实际发生的行为,以及您预期会发生的情况。输入文件只是有随机文本要测试,例如,Hello World,所以您回答了提出的3个问题中的第一个…使用循环,例如while(1==fscanf(in,“%c”,&ch))printf(“%c”,ch)代码>读取fscanf手册页“100是要打印的最大字符数”No.一个字节用于终止空字符,因此最大为99个字符,包括换行符(如果存在)。此外,使用幻数也不好,使用fgets()
的行应为fgets(text,sizeof(text),fp)代码>添加错误检查将使代码更好。sizeof(100)
->sizeof text
最好不要测试feof
。请解释。
The contents of the file are
Hello World