gpt4 book ai didi

C 仅使用 stdio 库将文件内容读取为字符串

转载 作者:行者123 更新时间:2023-11-30 21:27:30 26 4
gpt4 key购买 nike

我正在努力尝试将文件内容读入字符串(char*)。我只需要使用 stdio.h 库,所以我无法使用 malloc 分配内存。

如何读取文件的所有内容并将其返回为字符串?

最佳答案

我会尝试回答你的问题。但请记住 - 我对 C 还很陌生,所以可能有更好的解决方案,在这种情况下也请让我知道! :)

编辑:还有......

这是我的看法...您需要知道要存储在字符串中的文件的大小。更准确地说 - 在我提供的示例解决方案中,您需要知道输入文件中有多少个字符。

您使用malloc所做的就是在“堆”上动态分配内存。我想你已经知道了...因此,无论您的 string 位于内存中的哪个位置(堆栈或堆),您都需要知道该 string 必须有多大,因此输入文件的所有内容都会融入其中。

这里有一个快速的伪代码和一些可以解决您的问题的代码...我希望这有帮助,如果有更好的方法,我愿意学习更好的方法,和平!

伪代码:

  1. 打开输入文件进行读取

  2. 找出文件的大小

    • forward seek file position indicator to the end of the file

    • get the total number of bytes (chars) in infile

    • rewind file position indicator back to the start (because we will be reading from it again)

  3. 声明一个字符数组,大小为 - infile 中所有计数的字符 + 1(对于 '\0')在字符串的末尾。

  4. 将infile的所有字符读入数组

  5. 以“\0”结束字符串

  6. 关闭输入文件

这是一个简单的程序,它可以执行此操作并打印您的字符串:

#include <stdio.h>

int main(void)
{
// Open input file
FILE *infile = fopen("hello.py", "r");
if (!infile)
{
printf("Failed to open input file\n");
return 1;
}

////////////////////////////////
// Getting file size

// seek file position indicator to the end of the file
fseek(infile, 0L, SEEK_END);

// get the total number of bytes (chars) in infile
int size = ftell(infile); // ask for the position

// Rewind file position indicator back to the start of the file
rewind(infile);

//////////////////////////////////

// Declaring a char array, size of - all the chars from input file + 1 for the '\0'
char str[size + 1];

// Read all chars of infile in to the array
fread(&str, sizeof(char), size, infile);

// Terminate the string
str[size] = '\0'; // since we are zero indexed 'size' happens to be the last element of our array[size + 1]

printf("%s\n", str);

// Close the input file
fclose(infile);

// The end
return 0;

}

关于C 仅使用 stdio 库将文件内容读取为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50257645/

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