我正在尝试用 C 编写一个函数,它从文件中读取一些用逗号分隔的值,每行有 4 个值,最后一个是整数,我想将它们放在分配的空间中。当我尝试在 while 循环中从内存中读取它们时,它们很好,但是从 for 循环或函数外部,我多次得到文件的最后一行,在少数情况下它们会丢失一些字符。我是 C 新手,但我认为它与strtok()
功能有关。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
char * foo;
char * bar;
char * baz;
int qux;
}structure;
char * readFile(const char * filename, structure * array){
const int maxstring=100;
FILE * fr=fopen(filename,"r");
char * rc;
char buf[maxstring];
while(( rc = fgets(buf, maxstring, fr) )) {
array->foo=strtok (buf,",");
array->bar=strtok (NULL,",");
char *aux=strtok (NULL,",");
array->qux=atol(strtok (buf,","));
array->baz=strtok(aux,"\n");
printf("%s,%s,%s,%d\n",array->foo,array->bar,
array->baz,array->qux);
array++;
}
array=array-9;
for (int i=0;i<10;i++){
printf("%s,%s,%s,%d\n",array->foo,array->bar,
array->baz,array->qux);
array++;
}
return "Success";
}
int main(){
structure * array=malloc(100*sizeof(structure));
readFile("repository.txt",array);
free(array);
return 0;
}