我试图逐行阅读文本文件,并且试图将每个单词分配给一个列表。用该列表做些事情。完成此操作后,我将转到下一行。

#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
    }
}

最佳答案

您可以使用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]);
    }
}

关于c - 逐行读取文件并捕获该行的单词,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54497974/

10-11 15:33