[英]How to read a .txt file into C array line by line?
我有一个名为Members.txt
的.txt文件,其中包含:
2
Rebaz salimi 3840221821 0918888888
Hojjat Qolami 2459816431 09177777777
我已经编写了一个C文件,将Members.txt
读入char w[100];
数组像:
int main()
{
int i = 0, line = 5;
char w[100];
char f[20];
char k[15];
FILE *myfile;
myfile = fopen("Members.txt","r");
if (myfile== NULL)
{
printf("can not open file \n");
return 1;
}
while(line--){
fscanf(myfile,"%s",&w[i]);
i++;
printf("\n%s", &w[i]);
}
fclose(myfile);
return 0;
}
但是,我需要将Members.txt
每个换行符Members.txt
保存到不同的数组中。
如果您想读取文件并存储在数组内部,这是解决方案,您不能在数组内部存储,但是可以在数组内部存储。 在这里,我使您可以访问100行文本文件。 无论如何,这是代码:
#include <stdio.h>
//Use Structure to store more than one data type
//Since your file not only consist of string, it also have int
struct members
{
char a[100];
char b[100];
long long int c;
long long int d;
};
//Here I make 100 line so that you can read 100 line of text file
struct members cur_member[100];
int main(void) {
FILE *myfile = fopen("Members.txt", "r");
if (myfile == NULL) {
printf("Cannot open file.\n");
return 1;
}
else {
//Check for number of line
char ch;
int count = 0;
do
{
ch = fgetc(myfile);
if (ch == '\n') count++;
} while (ch != EOF);
rewind(myfile);
//Since you put 2 earlier in the member.txt we need to dump it
//so that it wont affect the scanning process
int temp;
fscanf(myfile, "%d", &temp);
printf("%d\n", temp);
//Now scan all the line inside the text
int i;
for (i = 0; i < count; i++) {
fscanf(myfile, "%s %s %lld %lld\n", cur_member[i].a, cur_member[i].b, &cur_member[i].c, &cur_member[i].d);
printf("%s %s %lld %lld\n", cur_member[i].a, cur_member[i].b, cur_member[i].c, cur_member[i].d);
}
}
}
结果如下:
2
Rebaz salimi 3840221821 918888888
Hojjat Qolami 2459816431 9177777777
Press any key to continue . . .
该程序将读取您的当前文件,而我只是将其打印出来,以显示其工作原理。 您可以访问信息并编辑文件。 就这样..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.