如何将文件中的文本读入数组,然后打印出整个数组

How to read text from a file into an array and then print the whole array out

好的!对这些东西很陌生!

这是一项更大任务的一部分,我现在遇到的问题是我在文本文件中有一个名称列表(100 个名称)。他们是这样写的:

Sam(输入)Oliver(输入)Paul(输入)---等等。

所以每个名字都在自己的行中。我正在尝试将其读入一个 char 数组,然后将其打印出来以检查它是否有效。之后我必须对它做一些其他事情,但我想稍后再解决。 这是我现在的代码:(文件名等是芬兰语,所以不要打扰它!:D)

#include <stdio.h>

int main() {
    FILE *tiedosto;
    char *array[100];
    char nimi[] = "names.txt";

    tiedosto = fopen(nimi, "r");

    if (tiedosto == NULL) {
        printf("Tiedostoa ei voida avata");
        return;
    }

    int i;
    for (i = 0; i < 100; i++) {
        fscanf(tiedosto, "%s", &array[i]);
    }
    fclose(tiedosto);

    printf("Tulostetaan taulukko \n");
    // printf("%s \n",array);

    for (i = 0; i < 100; i++) {
        printf("%s \n", array[i]);
    }

    return 0;
}

您的代码有几个错误:

  1. 这一行:

    fscanf(tiedosto, "%s", &array[i]);
    

    您不需要在此处使用符号。这是因为 array 已经是 char*[] 的类型——在这种情况下,您必须避免传递 char**.

  2. 在下面的代码段中:

    if (tiedosto == NULL) {
        printf("Tiedostoa ei voida avata");
        return; // ***
    }
    

    main()的return类型是一个整数,所以它必须传递一些非空的东西。任何非零 return 代码都表示程序关闭失败。

  3. 在此声明中:

    char *array[100];
    

    array 也在数组旁边使用指针。因此,必须正确使用 malloc() 函数对其进行初始化,以免遇到段错误。

    如果您不想弄乱分配内存等,请尝试切换到二维数组声明:

    char array[TOTAL_ENTRIES][PER_NAME_LEN];
    

我已经描述了二维数组方法来避免代码复杂性(阅读评论以获得解释):

#include <stdio.h>

// Some global macros throughout this program
#define MAX_USERS    100
#define MAX_STRLEN   64

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

int main(void) {
    const char *file_name = "names.txt";
    FILE *fp = fopen(file_name, "r");
    char name_list[MAX_USERS][MAX_STRLEN];
    int count = 0;

    // Using perror() is the best option here
    if (fp == NULL) {
        perror(file_name);
        return EXIT_FAILURE;
    }

    // Reading the file contents and saving that into 2-D array
    while (fscanf(fp, "%s", name_list[count++]) != EOF)
        ;

    // Displaying the saved array contents        
    for (int i = 0; i < count - 1; i++)
        fprintf(stdout, "%s\n", name_list[i]);

    return 0;
}

在此程序中,names.txt 文件中的行数可以小于或等于 100。