![](/img/trans.png)
[英]How to read data from a text file and store it in a variable in C language?
[英]read from a file and store it in a variable c
我正在嘗試從文件中逐字符准備好並將其存儲在變量中。 我只需要文件的第一行,所以我使用'\\ n'或EOF停止讀取字符,並且我還需要存儲空格。 聽到是我的程序,但是我在編譯時得到警告,例如指針和整數之間的比較。當我運行時,我遇到了段錯誤
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp;
char ch;
char txt[30];
int len;
fp=fopen("~/hello.txt","r");
ch=fgetc(fp);
while(ch != EOF || ch!="\n")
{
txt[len]=ch;
len++;
ch=fgetc(fp);
}
puts(txt);
}
您正在與錯誤的事物進行比較。 嘗試:
ch != '\n'
^ ^
另外,正如在其他答案中所發現的那樣,您正在使用len
而不進行初始化。
最后,您確實意識到fgets
也可以做到這一點。 您可以將其重寫為:
if (fgets(txt, sizeof txt, fp))
...
1) len
未啟動
int len=0;
2)從fgetc()頁面:
int fgetc ( FILE * stream );
因此fgetc()
返回int
而不是char
因此您必須將ch
定義為int
int ch;
3)除引號外 , while
條件應使用&&
而不是||
檢查。 :
while(ch != EOF && ch!='\n')
4)從文件讀取完成后,必須在txt
緩沖區的末尾添加null終止符。
在while
循環后添加此行
txt[len]='\0';
順便說一句,您可以使用fscanf()
閱讀第一行,它更容易。 只需使用以下代碼
fscanf(fp, "%29[^\n]", txt);
"%[^\\n]"
意味着fscanf
將從fp
讀取除'\\n'
字符以外的所有字符,如果得到該字符,它將停止讀取。 因此, fscanf
將讀取fp
所有字符,直到找到'\\n'
字符,並將其保存到緩沖區txt
中,最后使用null終止符。
"%29[^\\n]"
意味着fscanf
將從fp
讀取所有字符,直到找到'\\n'
字符或直到達到29個已讀字符為止,然后將它們保存到緩沖區txt
中,最后使用空終止符。
len
沒有初始化,因此您可能正在嘗試寫txt
末尾以外的內容。 修復很簡單-聲明時將其初始化為0
int len = 0;
除了cnicutar指出的錯誤外,還應該在使用fp
之前檢查fopen
的返回值。
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp;
char ch;
char txt[30];
int len = 0;
fp=fopen("~/hello.txt","r");
if(!fp) {
printf("Cannot open file!\n");
return;
}
ch=fgetc(fp);
while(ch != EOF && ch!= '\n' && len < 30)
{
txt[len] = ch;
len++;
ch=fgetc(fp);
}
txt[len] = 0;
puts(txt);
}
該程序可以幫助您解決問題。
#include<stdio.h>
int main()
{
FILE *fp;
int ch;
char txt[300];
int len=0;
fp=fopen("tenlines.txt","r");
do{
ch=fgetc(fp);
txt[len]=ch;
len++;
} while(ch!=EOF && ch!='\n');
fclose(fp);
puts(txt);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.