c - 数组替换我不想要的元素
问题描述
我想将每个单词放在一个数组中。
这是代码。
这是输出
据我所知,每次我有一个新行时,数组的第一个单词都会被文件下一行的第一个单词替换,但我不明白为什么。我在这里没有显示,但是在新行之后,所有其他位置都是错误的。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_LINE_LEN 256
void usage (const char *prog) {
fprintf (stderr, "Usage (words): %s [file_path]\n", prog);
exit (1);
}
void split_print_words (const char *filename) {
FILE *fd = stdin; // By default will read from stdin
if (filename != NULL && strcmp (filename, "-") != 0) {
// A file name was given, let's open it to read from there
fd = fopen (filename, "r");
assert (fd != NULL);
}
char buffer[MAX_LINE_LEN];
while(fgets(buffer, sizeof(buffer), fd != NULL)) {
char *token;
token = strtok(buffer, " \n");
while(token!=NULL) {
write(1, token, strlen(token));
write(1, "\n", 1);
token = strtok(NULL, " \n");
}
}
}
int main (int argc, char *argv[]) {
// Check there is one and only one argument
if (argc < 1 || argc > 2) {
usage (argv[0]);
}
split_print_words (argv[1]);
exit (0);
}
解决方案
正如评论中指出的那样,您应该替换它:
while(fgets(buffer, sizeof(buffer), fd != NULL)) {
有了这个:
while((fgets(buffer, sizeof(buffer), fd)) != NULL) {
我不确定您是如何设置编译器的。当我编译你的代码时,我显然收到了来自 gcc 的警告:
arrayreplace.c: In function ‘split_print_words’:
arrayreplace.c:27:48: warning: passing argument 3 of ‘fgets’ makes pointer from integer without a cast [-Wint-conversion]
27 | while(fgets(buffer, sizeof(buffer), fd != NULL)) {
| ^
| |
| int
In file included from arrayreplace.c:3:
/usr/include/stdio.h:564:69: note: expected ‘FILE * restrict’ but argument is of type ‘int’
564 | extern char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
| ~~~~~~~~~~~~~~~~~^~~~~~~~
进行此更改后,我能够看到从文件中解析的所有单词:
src : $ cat wordsarr.txt
This ia a
test and is
not working
src : $ ./a.out wordsarr.txt
This
ia
a
test
and
is
not
working
推荐阅读
- css - 在本地使用 Angular 9 材质样式
- javascript - 如何使用谷歌图表绘制 CSV 数据文件?
- c# - SQLite 查询未在 WPF 项目中正确执行
- javascript - 使用上下文和reducer在React中删除数组中的项目
- azure-devops-server-2019 - Azure Devops Server 无法连接到代理后面的服务挂钩
- arrays - 从二进制数组输入确定布尔方程
- sql - 包含产品销售额和数量的表 - 添加计算产品的列
- java - 从 HashMap 获取值并填充 Java 对象
- android - 我无法通过其 ID 或标签找到片段
- unity3d - Hololens 2 上的 LocatableCamera (PhotoCapture)