首页 > 解决方案 > 逐行读取文件并捕获该行单词

问题描述

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

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

标签: cfileiofgets

解决方案


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

推荐阅读