c语言操作文件
今天逛论坛时,看到了此问题,不要小看哦。
问题:
现想用c语言处理文本文件,主要函数buildRecord()不知道该怎么写,它的作用是从result.txt文本中获取一行字符后,构建一个Record
result.txt里面保存着学校,得分项目数,时间(小时),每行记录占据一行,每条记录里面的学校名,得分项目数,时间之间有空格,空格数目不定。例如:
Peking 3 1.5
Hust 5 9
Fudan 6 8
#include <stdio.h>
#include <string.h>
typedef struct RECORD
{
char school[10];
int scoreNumber;
float time;
} RECORD;
RECORD record[12];
void buildRecord(int i, char *buffer)
{
//TODO
}
void main()
{
FILE *p;
char ch;
int i = 0;
char buffer[50];
p = fopen("result.txt", "r");
if (p == NULL)
{
printf("cannot open file");
exit(0);
}
//TODO
fclose(p);
}
#include <string.h>
typedef struct RECORD
{
char school[10];
int scoreNumber;
float time;
} RECORD;
RECORD record[12];
void buildRecord(int i, char *buffer)
{
//TODO
}
void main()
{
FILE *p;
char ch;
int i = 0;
char buffer[50];
p = fopen("result.txt", "r");
if (p == NULL)
{
printf("cannot open file");
exit(0);
}
//TODO
fclose(p);
}
以下是我的回复,自己大体写了一下,还有欠缺,不允许校名里有空格,起个抛砖引玉的作用吧,希望各路高手不吝赐教。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 50
#define RECORDSIZE 12
typedef struct RECORD
{
char *school;
int scoreNumber;
float time;
} RECORD;
RECORD record[RECORDSIZE];
FILE *p;
int buildRecord(int &count,char *buffer)//返回值为记录条数
{
//TODO
char *ch;
char *delim=" ";
bool isScore;//分离scoreNumber和time时使用
int i=0;
while(fgets(buffer,BUFFERSIZE,p))
{
count++;
isScore=true;
record[i].school=strtok(buffer,delim);
while(ch=strtok(NULL,delim))
{
if(isScore)
{
record[i].scoreNumber=atoi(ch);
isScore=false;
}
else
{
record[i].time=atof(ch);
}
}
printf("Record-%i: school:%s scoreNumber:%i time:%5.2f\n",i,record[i].school,record[i].scoreNumber,record[i].time);
i++;
}
return count;
}
void main()
{
char buffer[BUFFERSIZE];
int count=0;
p = fopen("e:/result.txt", "r");
if (p == NULL)
{
printf("cannot open file");
exit(0);
}
count=buildRecord(count,buffer);
printf("Record total number is %i",count);
//TODO
fclose(p);
getchar();
}
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 50
#define RECORDSIZE 12
typedef struct RECORD
{
char *school;
int scoreNumber;
float time;
} RECORD;
RECORD record[RECORDSIZE];
FILE *p;
int buildRecord(int &count,char *buffer)//返回值为记录条数
{
//TODO
char *ch;
char *delim=" ";
bool isScore;//分离scoreNumber和time时使用
int i=0;
while(fgets(buffer,BUFFERSIZE,p))
{
count++;
isScore=true;
record[i].school=strtok(buffer,delim);
while(ch=strtok(NULL,delim))
{
if(isScore)
{
record[i].scoreNumber=atoi(ch);
isScore=false;
}
else
{
record[i].time=atof(ch);
}
}
printf("Record-%i: school:%s scoreNumber:%i time:%5.2f\n",i,record[i].school,record[i].scoreNumber,record[i].time);
i++;
}
return count;
}
void main()
{
char buffer[BUFFERSIZE];
int count=0;
p = fopen("e:/result.txt", "r");
if (p == NULL)
{
printf("cannot open file");
exit(0);
}
count=buildRecord(count,buffer);
printf("Record total number is %i",count);
//TODO
fclose(p);
getchar();
}