gpt4 book ai didi

arrays - 动态分配内存到数组并读取大文本文件

转载 作者:行者123 更新时间:2023-12-03 08:38:03 26 4
gpt4 key购买 nike

我看过其他一些类似的问题和示例,但我很困惑。我的目标是打开一个非常大的文本文件(小说大小),为数组分配内存,然后将文本存储到该数组中,以便我将来能够进行进一步的处理。

这是我当前的代码:

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

#define LINELEN 74

int main(void) {

FILE *file;
char filename[] = "large.txt";
int count = 0, i = 0, len;

/* Open the file */
file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file");
return -1;
}

/* Get size of file for memory allocation */
fseek(file, 0, SEEK_END);
long size = ftell(file);
fseek(file, 0, SEEK_SET);

/* Allocate memory to the array */
char *text_array = (char*)malloc(size*sizeof(char));

/* Store the information into the array */
while(fgets(&text_array[count], LINELEN, file) != NULL) {
count++;
}

len = sizeof(text_array) / sizeof(text_array[0]);

while(i<len) {
/* printf("%s", text_array); */
i++;
}
printf("%s", text_array);

/* return array */
return EXIT_SUCCESS;
}

我期望从底部的 text_array 打印出大量文本。相反,我得到了一堆乱码的随机字符,比我希望的文本正文小得多。我究竟做错了什么?我怀疑这与我的内存分配有关,但不知道是什么。

非常感谢任何帮助。

最佳答案

无需在循环中调用fgets()。您知道文件有多大,只需一次调用即可将整个文件读入 text_array 中:

fread(text_array, 1, size, file);

但是,如果要将 text_array 视为字符串,则需要添加空终止符。所以调用malloc()时应该加1。

另一个问题是len = sizeof(text_array)/sizeof(text_array[0])text_array 是一个指针,而不是数组,因此您不能使用 sizeof 来获取它使用的空间量。但您不需要这样做,因为 size 变量中已经有空间。

无需在循环中打印 text_array

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

#define LINELEN 74

int main(void) {

FILE *file;
char filename[] = "large.txt";
int count = 0, i = 0, len;

/* Open the file */
file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file");
return -1;
}

/* Get size of file for memory allocation */
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
fseek(file, 0, SEEK_SET);

/* Allocate memory to the array */
char *text_array = (char*)malloc(size*sizeof(char) + 1);

/* Store the information into the array */
fread(text_array, 1, size, file);
text_array[size] = '\0';
printf("%s", text_array);

/* return array */
return EXIT_SUCCESS;
}

关于arrays - 动态分配内存到数组并读取大文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63353054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com