从文件中读取未知数量的字符串(每个字符串的长度未知)后,如何创建 char* 数组?

发布于 2025-01-11 22:57:08 字数 1905 浏览 5 评论 0原文

我有一个包含未知数量字符串的文件,并且每个字符串的长度都未知。 我想让文件的每一行在字符串数组中都有自己的字符串。

我尝试在 char** 数组中使用动态分配,但我认为我没有正确处理这个问题。

下面是我尝试过的代码。它陷入了无限循环,我不明白为什么。 (顺便说一句,我正在读取的文本文件以换行符结尾。)

#include <getopt.h> //for getopts 
#include <sys/stat.h> //to do file stat
#include <dirent.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h> //user macros
#include <stdlib.h>
#include <stdbool.h>
#include <libgen.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    //storing the filename inside string
    char* filename = argv[1];


    FILE *fp1 = fopen(filename, "r");
    if (fp1 == NULL) {
        fprintf(stderr, "Error: Cannot open '%s'. No such file or directory.\n", filename);
        return EXIT_FAILURE;
    }
    
    /**
     * we begin by getting the number of numbers in the file
     * the number of numbers = number of lines = number of line breaks
     */
    size_t numNumbers = 0;

    // while((fscanf(fp1, "%*[^\n]"), fscanf(fp1, "%*c")) != EOF){
    //     numNumbers = numNumbers + 1;
    // }
    char c;
    while((c = fgetc(fp1)) != EOF){
        if(c == '\n'){
            numNumbers++;
        }
    }

    fclose(fp1); 

    FILE *fp2 = fopen(filename, "r");
    char** arrayOfStrings = malloc(numNumbers * sizeof(char*));

    for(int i = 0; i < numNumbers; i++) {
        int len = 0;
        if(((c = fgetc(fp1)) != '\n') && (c != EOF)){
            len++;
        }
        arrayOfStrings[i] = malloc(len * sizeof(char));
    }

    printf("hello1\n");

    //for(int i = 0; i < numNumbers; i++){
    //    fscanf(fp2, "%s", (arrayOfStrings[i]));
    //}

    fclose(fp2);

    // for(int i = 0; i < numNumbers; i++){
    //     fprintf(stdout, "%s", arrayOfStrings[i]);
    // }
    return 0;
}

(我对 C 很陌生,所以请对我宽容点!)

I have a file with an unknown number of strings and each of these strings is of an unknown length.
I would like to make each line of the file its own string in an array of strings.

I tried to use dynamic allocation in a char** array, but I don't think I'm approaching this correctly.

Below is the code I have tried. It's getting stuck in an infinite loop, and I can't figure out why.
(The text file I'm reading from ends with a line break, by the way.)

#include <getopt.h> //for getopts 
#include <sys/stat.h> //to do file stat
#include <dirent.h>
#include <string.h>
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h> //user macros
#include <stdlib.h>
#include <stdbool.h>
#include <libgen.h>
#include <errno.h>

int main(int argc, char *argv[]) {
    //storing the filename inside string
    char* filename = argv[1];


    FILE *fp1 = fopen(filename, "r");
    if (fp1 == NULL) {
        fprintf(stderr, "Error: Cannot open '%s'. No such file or directory.\n", filename);
        return EXIT_FAILURE;
    }
    
    /**
     * we begin by getting the number of numbers in the file
     * the number of numbers = number of lines = number of line breaks
     */
    size_t numNumbers = 0;

    // while((fscanf(fp1, "%*[^\n]"), fscanf(fp1, "%*c")) != EOF){
    //     numNumbers = numNumbers + 1;
    // }
    char c;
    while((c = fgetc(fp1)) != EOF){
        if(c == '\n'){
            numNumbers++;
        }
    }

    fclose(fp1); 

    FILE *fp2 = fopen(filename, "r");
    char** arrayOfStrings = malloc(numNumbers * sizeof(char*));

    for(int i = 0; i < numNumbers; i++) {
        int len = 0;
        if(((c = fgetc(fp1)) != '\n') && (c != EOF)){
            len++;
        }
        arrayOfStrings[i] = malloc(len * sizeof(char));
    }

    printf("hello1\n");

    //for(int i = 0; i < numNumbers; i++){
    //    fscanf(fp2, "%s", (arrayOfStrings[i]));
    //}

    fclose(fp2);

    // for(int i = 0; i < numNumbers; i++){
    //     fprintf(stdout, "%s", arrayOfStrings[i]);
    // }
    return 0;
}

(I'm very new to C, so please go easy on me!)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若有似无的小暗淡 2025-01-18 22:57:08

在 C 中,字符串以“0”字节终止,因此看起来每个字符串的 malloc 都太短了 1 个字符——您只为文本留出了空间。

此外,您的意思是每行大小的计数是一个 while 循环,而不是 if 语句 - 现在您将每行计数为长度“1”。

最后,您在注释掉的 fscanf 代码中读取了文件的末尾,因为您尚未关闭并重新打开它。

In C, strings are terminated with a '0' byte, so it looks like your malloc for each string is 1 character too short -- you've only allowed space for the text.

In addition, you mean the count for the size of each line to be a while loop, not an if statement - right now you are counting each line as length "1".

Finally, you are reading off the end of the file in your commented out fscanf code because you haven't closed and reopened it.

剩一世无双 2025-01-18 22:57:08

假设您想通过换行符将输入拆分为字符串,请尝试:

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

int main(int argc, char *argv[])
{
    char *filename;                     // filename to read
    char **arrayOfStrings = NULL;       // array of strings
    char line[BUFSIZ];                  // line buffer while reading
    char *p;                            // temporal pointer to the input line
    int i, num;                         // counter for lines
    FILE *fp;                           // file pointer to read

    if (argc != 2) {
        fprintf(stderr, "usage: %s file.txt\n", argv[0]);
        return EXIT_FAILURE;
    }
    filename = argv[1];
    if (NULL == (fp = fopen(filename, "r"))) {
        perror(filename);
        return EXIT_FAILURE;
    }
    // read the input file line by line
    while (fgets(line, BUFSIZ, fp)) {
        if ((p = strrchr(line, '\n'))) *p = '\0';       // remove trailing newline, if any
        if ((p = strrchr(line, '\r'))) *p = '\0';       // remove trailing cr character, if any

        if (NULL == (arrayOfStrings = realloc(arrayOfStrings, (num + 1) * sizeof(char **)))) {
                                                        // enlarge the array according to the line count
            perror("realloc");
            return EXIT_FAILURE;
        }
        if (NULL == (arrayOfStrings[num] = malloc(strlen(line) + 1))) {
                                                        // memory for the string of the line
            perror("malloc");
            return EXIT_FAILURE;
        }
        strcpy(arrayOfStrings[num], line);
        num++;
    }

    // print the strings in the array
    for (i = 0; i < num; i++) {
        printf("%d %s\n", i, arrayOfStrings[i]);
    }

    fclose(fp);
    return 0;
}

如果输入文件看起来像:

This
is
the
input.

那么输出将是:

0 This
1 is
2 the
3 input.

Assuming you want to split the input to the strings by the newline character, would you please try:

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

int main(int argc, char *argv[])
{
    char *filename;                     // filename to read
    char **arrayOfStrings = NULL;       // array of strings
    char line[BUFSIZ];                  // line buffer while reading
    char *p;                            // temporal pointer to the input line
    int i, num;                         // counter for lines
    FILE *fp;                           // file pointer to read

    if (argc != 2) {
        fprintf(stderr, "usage: %s file.txt\n", argv[0]);
        return EXIT_FAILURE;
    }
    filename = argv[1];
    if (NULL == (fp = fopen(filename, "r"))) {
        perror(filename);
        return EXIT_FAILURE;
    }
    // read the input file line by line
    while (fgets(line, BUFSIZ, fp)) {
        if ((p = strrchr(line, '\n'))) *p = '\0';       // remove trailing newline, if any
        if ((p = strrchr(line, '\r'))) *p = '\0';       // remove trailing cr character, if any

        if (NULL == (arrayOfStrings = realloc(arrayOfStrings, (num + 1) * sizeof(char **)))) {
                                                        // enlarge the array according to the line count
            perror("realloc");
            return EXIT_FAILURE;
        }
        if (NULL == (arrayOfStrings[num] = malloc(strlen(line) + 1))) {
                                                        // memory for the string of the line
            perror("malloc");
            return EXIT_FAILURE;
        }
        strcpy(arrayOfStrings[num], line);
        num++;
    }

    // print the strings in the array
    for (i = 0; i < num; i++) {
        printf("%d %s\n", i, arrayOfStrings[i]);
    }

    fclose(fp);
    return 0;
}

If the input file looks something like:

This
is
the
input.

Then the output will be:

0 This
1 is
2 the
3 input.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文