现有一个文件ped.txt,里面有三列数据,格式如下:
ahdfs shdje sjdjf
sdhfh hdier dfue
我想从文件中读入,在原样输出。
有个函数叫做strtok,用法如下,可以判断读文件中的空格
#include "stdio.h"
#include "string.h"
struct student
{
char name[20];
int age;
char address[20];
char telnum[10];
};
main()
{
FILE *rfp,*wfp;
char *tfile=".\\data.txt";
char *bfile=".\\data_out.txt";
char seps[]=" \n";
char text[100],temp[100];
int i,index,num;
char *token;
struct student person[10];
if((rfp=fopen(tfile,"r"))==NULL)
printf("%s could not be opened!\n",tfile);
if((wfp=fopen(bfile,"w"))==NULL)
printf("%s could not be opened!\n",bfile);
num=0;
while(!feof(rfp))
{
fgets(text,100,rfp);
token=strtok(text,seps);
index=0;
while(token&&*token!='\x0a')
{
switch(index)
{
case 0: strcpy((person+num)->name,token);break;
case 1: (person+num)->age=atoi(token);break;
case 2: strcpy((person+num)->address,token);break;
default:strcpy((person+num)->telnum,token);
}
token=strtok(NULL,seps);
index++;
}
num++;
}
i=0;
while(i<num)
{
fprintf(wfp,"%s ",(person+i)->name);
fprintf(wfp,"%d ",(person+i)->age);
fprintf(wfp,"%s ",(person+i)->address);
fprintf(wfp,"%s\n",(person+i)->telnum);
i++;
}
fclose(rfp);
fclose(wfp);
}