[英]Why doesnt my C program work? reading from a file
我是 C 編程新手,我正在嘗試編寫一個程序來讀取名為 input.txt 的文件的上下文。
#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;
}
您的代碼僅讀取文件的第一個字符。 沒有循環讀取整個文件。 這就是你的意圖嗎?
另外,檢查文件打開是否成功。 輸入文件名是“input”嗎?
嘗試這個 -
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
的內容是:
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;
}
輸出:
The contents of the file are
Hello World
你應該使用這個:
#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;
}
您應該記住驗證文件是否打開,這始終是一個好習慣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.