gpt4 book ai didi

c - 将文本文件读入字符数组

转载 作者:行者123 更新时间:2023-12-04 11:45:59 25 4
gpt4 key购买 nike

我在将文本放入 char 数组时遇到了一些问题。当我为数组设置静态大小时它工作正常

char speech[15000];

但这效率很低,所以我尝试改用 calloc。这使它停止工作。该数组以正确的大小存在,但没有写入任何内容。这是相关代码。我做错了什么?

int main() {

FILE* inFile;
int i;
int count = 0;

printf("\nOpening file April_30_1789.txt\n");

inFile = fopen("./speeches/April_30_1789.txt", "r");

if(inFile == NULL) {
printf("Could not find April_30_1789.txt\n");
return -1;
}

char ch;

while((ch = fgetc(inFile) != EOF)) count++;

rewind(inFile);

int size = count;

printf("Size of the array is %d\n", size);

char *speech = (char *)malloc(size*sizeof(char) + 1*sizeof(char));

fscanf(inFile, "%s", speech);

printf("Closing the file.\n");
fclose(inFile);

printf("%s", speech);

printf("\n\nDone\n");

return 0;

}

目前,这给了我

Opening file April_30_1789.txt
Size of the array is 8617
Closing the file.
Fellow-Citizens

Done

最佳答案

Reading the whole text file into a char array in C 可能重复.


您的问题:"%s" 格式的fscanf 将读取到遇到的第一个空格。

可能的解决方案(为简洁起见省略了错误检查):

#include <stdio.h>  /* printf */
#include <stdlib.h> /* fopen, fseek, ... */

char *buffer = NULL;
size_t size = 0;

/* Open your_file in read-only mode */
FILE *fp = fopen("your_file_name", "r");

/* Get the buffer size */
fseek(fp, 0, SEEK_END); /* Go to end of file */
size = ftell(fp); /* How many bytes did we pass ? */

/* Set position of stream to the beginning */
rewind(fp);

/* Allocate the buffer (no need to initialize it with calloc) */
buffer = malloc((size + 1) * sizeof(*buffer)); /* size + 1 byte for the \0 */

/* Read the file into the buffer */
fread(buffer, size, 1, fp); /* Read 1 chunk of size bytes from fp into buffer */

/* NULL-terminate the buffer */
buffer[size] = '\0';

/* Print it ! */
printf("%s\n", buffer);

关于c - 将文本文件读入字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22697407/

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