从文本文件获取输入并添加数组

问题描述 投票:0回答:1

我是C语言的新手。我想为我的代码创建一个数组来进行一些操作。正如我上面所说,我正在努力学习如何有效地使用C语言。我的问题是:我有一个输入文件,让我们说input.txt。我知道每一行都有4种不同的东西,其中2种是字符串,其中2种是数字。另外,我想创建一个2D数组。但我不知道输入文件中会有多少行。这取决于用户。所以,我必须使用malloc动态制作我的数组。那么,你能帮我解决这个问题吗?也许这很容易,但我认为读取文件并在C中创建一些数组比其他语言更难。在Python中它很容易:(我将我的代码留在下面。如果你告诉我我的错误,我会很高兴:)

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

int main(int argc, char const *argv[]) {
    char *arrChar;
    int i;
    char *str;
    char *token;
    arrChar = (char *) malloc( sizeof( char ) );
    str = (char *) malloc( sizeof( char ) );
    FILE *FileChars;
    FileChars = fopen( argv[1], "r");
    i = 0;
    while ( fgets(str, sizeof str, FileChars) != NULL) {
        int j;
        for ( j = 0; j < 4; j++ ) {
                token = strtok(str, ",");
                arrChar[i][j] = token;
            }
        i++;
         }
}
c file
1个回答
1
投票
  1. 你需要准确理解sizeof操作符的作用,它不返回动态分配的内存块的大小,它返回一个类型的大小,如果是数组 - 粗略地说 - 大小是类型规范的一部分,所以它返回数组占用的字节数。 在你的情况下,sizeof(char)char类型的大小,需要由( C标准)精确1。 sizeof(str)str类型的大小,它是char *,也就是指针的大小。根据您当前的平台,它可能是48。 要解决这个问题,你必须在整个程序中定义一个长度,作为分配的内存块的长度,确保分配成功后(见下文)。
  2. 指向char的指针可以指向一系列元素,如果它是正确的序列,则可以将其解释为字符串。一系列“可打印”字符后跟'\0'或null字符被视为字符串。
  3. 如果你要处理相同的字符串,你必须在第一次之后将NULL传递给strtok()
  4. 您应该通过将返回值与fopen()进行比较来检查NULL是否确实返回了有效的流。
  5. 与(5)相同,对于malloc(),当分配不可能时,返回NULL并将其用作有效指针是未定义的行为。

总而言之,这就是你想写的东西

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

#define NUM_WORDS 100

int main(int argc, char const *argv[])
{
    char *token;
    char **words;
    char line[100];
    char *ptr;
    size_t count;
    FILE *file;

    file = fopen( argv[1], "r");
    // Check that we DID open the file
    if (file == NULL) {
        perror(argv[1]);
        return EXIT_FAILURE;
    }

    // Allocate space for `NUM_WORDS' pointers
    words = malloc(NUM_WORDS * sizeof(*words));
    // Check that we did allocate enough memory
    if (words == NULL) {
        fclose(file);
        return EXIT_FAILURE;
    }

    // We use `sizeof' here because `line' is an array
    count = 0;
    while ((count < NUM_WORDS) && (fgets(line, sizeof(line), file) != NULL)) {
        ptr = line;
        do {
            token = strtok(ptr, ",");
            // We need to copy the `token' because
            // it lies within `line' and the '\0' will
            // be replaced by the original character
            // in subsequent callse to `strtok()'
            //
            // The `strdup()' will allocate enough space with
            // `malloc()' then copy the contents of `token' to the
            // allocated buffer, and return it, so we will
            // have to call `free()' on every `words' element.
            words[count++] = strdup(token);
            // Subsequent calls to `strtok()' with the same
            // string require that the first parameter is
            // NULL
            ptr = NULL;
         } while ((count < NUM_WORDS) && (token != NULL));
    }
    // Now we may print the words and free the memory
    for (size_t index = 0; index < count; ++index) {
        puts(words[index]);
        free(words[index]);
    }
    free(words);
    return 0;
}

注意上面的代码,确保我们不超过指针数组words1的容量。如果你需要调整它的大小,你将需要学习如何使用realloc()并在专门的例程中执行它,这样你的代码就不会变得太复杂。


1注意分配的空间没有预定义的解释,我们将其解释为数组,但它不是数组定义的意义上的数组,line是IS,具有char类型的元素,line也可以解释为给定的字符串它具有与上述第(2)点中给出的定义相容的内容。

© www.soinside.com 2019 - 2024. All rights reserved.