首页 > 解决方案 > 数组替换我不想要的元素

问题描述

我想将每个单词放在一个数组中。

我要打印的单词。

这是代码。

在此处输入图像描述

这是输出

在此处输入图像描述

据我所知,每次我有一个新行时,数组的第一个单词都会被文件下一行的第一个单词替换,但我不明白为什么。我在这里没有显示,但是在新行之后,所有其他位置都是错误的。

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

标签: cfilestrtok

解决方案


正如评论中指出的那样,您应该替换它:

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

推荐阅读