当前,我正在做一些实际的工作来拼贴巫婆,我必须从文件中读取数据。
文件数据结构是:“ id name sex”
示例:
nm0025630 Vikas Anand Mnm0418131维克多·詹森Mnm0411451迪克以色列Mnm0757820莱奥波多·萨尔塞多M
要阅读当前我正在使用此代码:
fh = NULL;
fh = fopen(ACTORS, "r");
if (!fh) {
exit(1);
}
while (!feof(fh)) {
char sex, name[100], id[10];
fgets(id, 10, fh);
fgets(name, 100, fh);
fgetc(sex);
if (!feof(fh)) {
hash_update_node(hash, get_id_num(id), name, sex);
count++;
}
}
问题在于,它会同时读取姓名和性别。任何帮助表示赞赏。
[fgets(name, 100, fh);
最多读取99个字符,当名称少于98个字符时,如果性别之前只有一个空格,则也会读取性别。
因为名称是由几个由空格隔开的单词组成,所以一种方式是先阅读所有行然后提取性别。
警告您第一次执行while (!feof(fh)) {
,此操作之前没有任何读取,因此feof
无法知道文件是否为空,然后知道是否达到EOF。我鼓励您通过阅读结果来检测EOF。
还因为您仅在if (!feof(fh)){
时保存读取的数据,所以您不记住最后一行的信息。
注意:如果有足够的地方,fgets
也保存换行符,使用fscanf
更实用。
所以一种方法可以是:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define ACTORS "/tmp/actors"
int main()
{
FILE * fh = fopen(ACTORS, "r");
if (!fh) {
perror("cannot read " ACTORS);
exit(1);
}
char name[100],id[10];
while (fscanf(fh, "%9s %99[^\n]", id, name) == 2) {
size_t sz = strlen(name);
char sex = name[--sz];
while ((sz != 0) && isspace(name[--sz]))
;
if (sz == 0) {
puts("empty name");
exit(2);
}
name[sz+1] = 0;
/*
hash_update_node(hash, get_id_num(id) , name, sex);
count++;
*/
printf("id='%s', name='%s', sex=%c\n", id, name, sex);
}
fclose(fh);
return 0;
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall r.c
pi@raspberrypi:/tmp $ ./a.out
cannot read /tmp/actors: No such file or directory
pi@raspberrypi:/tmp $ cat > actors
nm0025630 Vikas Anand M
nm0418131 Victor Janson M
nm0411451 Dick Israel M
nm0757820 Leopoldo Salcedo M
pi@raspberrypi:/tmp $ ./a.out
id='nm0025630', name='Vikas Anand', sex=M
id='nm0418131', name='Victor Janson', sex=M
id='nm0411451', name='Dick Israel', sex=M
id='nm0757820', name='Leopoldo Salcedo', sex=M
pi@raspberrypi:/tmp $
似乎文件中的字段由TAB字符分隔。如果正确,则可以使用fscanf()
:
#include <stdio.h>
#include <stdlib.h>
int local_file(void) {
char sex, name[100], id[10];
int count = 0;
FILE *fh = fopen(ACTORS, "r");
if (!fh) {
exit(1);
}
while (fscanf("%9[^\t]%*1[\t]%99[^\t]%*1[\t]%c", id, name, &sex) == 3) {
hash_update_node(hash, get_id_num(id), name, sex);
count++;
}
return count;
}
但是请注意,如果任何字段为空,则此代码将失败。