c - 逐行读取文件并捕获该行单词
问题描述
我试图逐行阅读文本文件,并且每一行我都试图将每个单词分配给一个列表。用那个列表做点什么。完成此操作后,我将转到下一行。
#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]);
}
}
推荐阅读
- excel - 从另一个单元格填充的动态数据验证列表
- python - 在 python 中更好的输入提示?
- python - Pip 不适用于 Ubuntu 上的 Python 3.10
- node.js - 错误未知身份验证策略“本地”
- android - Android:系统服务没有接口?
- c# - 如果 bool 为真,您可以在 if 函数中更改 bool 的值吗?
- r - 使用 row.names 组合多个 .csv 文件
- php - 如何在 Laravel 中汇总组集合?
- gitlab - 如何通过gitlab API获取项目指定的分支文件大小?
- ruby - 如何通过崎岖不平计算一个分支的所有代码行?