我不想要的数组替换元素

问题描述

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

Words that i'm trying to print.

这是代码

enter image description here

这是输出

enter image description here

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

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

解决方法

尝试一下(阅读评论):

#include <stdio.h>
#include <string.h>

#define MAX_LINE_LEN 256
#define WORDS_N 10

int main(void)
{
    FILE* fp;

    // Open the file and check if it was opened
    fp = fopen("myfile.txt","r");
    if (fp == NULL) {
      perror("Failed: ");
      return 1;
    }

    // Temporary buffer that will store one line of the file at a time
    char buffer[MAX_LINE_LEN];
    // NULL-initialized 2D array of size 'WORDS_N' x 'MAX_LINE_LEN'
    char words[WORDS_N][MAX_LINE_LEN] = {0};
    // Count how many words we actually read from the file
    int count = 0;
    // To be used by 'strtok()'
    char* pch;
    // Read file line by line
    while (fgets(buffer,MAX_LINE_LEN,fp))
    {
        // Remove trailing newline
        buffer[strcspn(buffer,"\n")] = 0;
        //printf("%s\n",buffer);

        // Split line by whitespace
        pch = strtok(buffer," ");
        // For each token in the split line
        while (pch != NULL)
        {
          // If the array has available space
          if(count < WORDS_N)
            // Put the current token into the array
            strcpy(words[count++],pch);
          //printf ("%s\n",pch);

          // Proceed to next token
          pch = strtok(NULL," ");
        }
    }

    // Print array
    for (int i = 0; i < count; ++i)
        printf("%s\n",words[i]);

    // Close file
    fclose(fp);
    return 0;
}

输入(myfile.txt):

This is a
test and is
not working!

输出:

This
is
a
test
and
is
not
working!
,

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

while(fgets(buffer,sizeof(buffer),fd != NULL)) {

与此:

while((fgets(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,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