C语言,读取每一行到字符串数组

文件大概是这样的
123456
12345
1234
abcdef
qwerty

行数不固定,每行的内容不会超过20字符
读取到一个字符串数组, 就像是argc argv那样

第1个回答  2011-08-22
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
FILE * fp;
char buf[30];
fp=fopen("./eg_file.txt","r");//打开文件,我是在linux下写的,你把fopen中的第一个参数写成windows下的绝对路径就好了。

while(fscanf(fp,"%s",buf)!=-1){//读取文件中的一行写入字符串数组buf中
printf("%s\n", buf);
}
fclose(fp);//关闭文件
return 0;
}
第2个回答  2011-08-22
#include <stdio.h>
#include <string.h>

void main()
{
FILE *file = fopen("1.txt","r+");
if ( NULL == file)
{
return;
}
char buf[21] = {0};
char c;
int i = 0;
while((c = getc(file)))
{
buf[i++] = c;
if (c == '\n' || c == EOF)
{

buf[i] = '\0';
printf("%s",buf);
memset(buf,0,sizeof(buf));
i = 0;
if (c == EOF)
{
printf("\n");
break;
}

}

}

}
第3个回答  2011-08-22
FILE *p=fopen("1.txt","r");
if(p==NULL)
return 0;
char a[20];
while(!feof(p))
{fscanf(p,"%s",a);
puts(a);
}
第4个回答  2011-08-23
qwerty
abcdef
1234
12345
123456
Press any key to continue
#include "stdio.h"
#include "string.h"
main()
{
int i=0;
char AA[10][10];
FILE *fp;
fp=fopen("data.txt","r");
if(fp==NULL)
{
printf("Open File error!");
}
else
{
char a[10];
while(!feof(fp))
{
fscanf(fp,"%s",a);
strcpy(AA[i++],a);//AA[i++] = a;
}
}
fclose(fp);
for (i--;i>=0;i--)
{
printf("%s\n",AA[i]);
}
}
本回答被提问者采纳
相似回答