简体   繁体   中英

How to use fscanf to read a text file including many words and store them into a string array by index

The wordlist.txt is including like:

able
army
bird
boring
sing
song

And I want to use fscanf() to read this txt file line by line and store them into a string array by indexed every word like this:

src = [able army bird boring sing song]

where src[0]= "able", src[1] = "army" and so on. But my code only outputs src[0] = "a", src[1] = "b"... Could someone help me figure out what's going wrong in my code:

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

int main(int argc, char *argv[])
{
    FILE *fp = fopen("wordlist.txt", "r");
    if (fp == NULL)
    {
        printf("%s", "File open error");
        return 0;
    }
    char src[1000];
    for (int i = 0; i < sizeof(src); i++)
    {
        fscanf(fp, "%[^EOF]", &src[i]);
    }
    fclose(fp);
    printf("%c", src[0]);
    getchar();
    return 0;
}

Pretty appreciated!

For example like this.

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

#define MAX_ARRAY_SIZE 1000
#define MAX_STRING_SIZE 100

int main(int argc, char *argv[]) {
    FILE *fp = fopen("wordlist.txt", "r");
    if (fp == NULL) {
        printf("File open error\n");
        return 1;
    }
    char arr[MAX_ARRAY_SIZE][MAX_STRING_SIZE];
    int index = 0;
    while (1) {
        int ret = fscanf(fp, "%s", arr[index]);
        if (ret == EOF) break;
        ++index;
        if (index == MAX_ARRAY_SIZE) break;
    }
    fclose(fp);
    for (int i = 0; i < index; ++i) {
        printf("%s\n", arr[i]);
    }
    getchar();
    return 0;
}

Some notes:

  • If there is an error, it is better to return 1 and not 0, for 0 means successful execution.
  • For a char array, you use a pointer. For a string array, you use a double pointer. A bit tricky to get used to them, but they are handy.
  • Also, a check of the return value of the fscanf would be great.
  • For fixed size arrays, it is useful to define the sizes using #define so that it is easier to change later if you use it multiple times in the code.

It's reading file one character at a time, Which itself is 4 in size like we see sizeof('a') in word able. Same goes for 'b' and so on. So one approach you can use is to keep checking when there is a space or newline character so that we can save the data before these two things as a word and then combine these small arrays by adding spaces in between and concatenating them to get a single array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM