我试图逐行阅读文本文件,并且试图将每一单词分配给一个列表。如何处理这些名单的东西。完成此操作后,我将转到下一行。
#define BUFSIZE 1000
int main(int argc, char* argv[]){
char buf[BUFSIZE];
FILE* fp;
fp=fopen(argv[1], "r"); //open the file
while(fgets(buf, BUFSIZE-1, fp)!= NULL){ //loop through each line of the file
char *myargs[5];
myargs[0]= ?? //some way to set the first word to this
myargs[4]= ?? //there will only be 4 words
myargs[5]=NULL;
//do something with myargs
}
}
答案 0 :(得分:0)
您可以使用strtok
将一行文本分隔为标记。假设每个单词都用空格隔开,您可以执行以下操作:
while(fgets(buf, BUFSIZE-1, fp)!= NULL){ //loop through each line of the file
char *myargs[4] = { NULL };
char *p;
int i, count = 0;
p = strtok(buf, " ");
while (p && (count < 4)) {
myargs[count++] = strdup(p);
p = strtok(NULL, " ");
}
// operate on myargs
for (i = 0; i < count; i++) {
free(myargs[i]);
}
}