【问题标题】:C Read file content into string just with stdio libary [closed]C仅使用stdio库将文件内容读入字符串[关闭]
【发布时间】:2018-10-19 19:46:37
【问题描述】:

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

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

【问题讨论】:

  • 有多种方法可以做到这一点。您要解决什么具体问题?
  • 你认为你为什么需要malloc
  • 提示:读取文件大小this
  • 如果您使用malloc 在此处发布您的解决方案并询问如何在没有它的情况下进行操作,那么这个问题可能看起来是合法的。
  • @reByte: 总是在你的问题中加入代码,除非它是一个简单、简短的陈述,否则永远不要在评论中。

标签: c linux file reader


【解决方案1】:

我将尝试回答您的问题。但请记住——我对 C 语言还是很陌生,所以可能有更好的解决方案,在这种情况下也请告诉我! :)

编辑:还有……

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

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

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

伪代码:

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

  2. 找出文件的大小

    • 向前寻找文件位置指示器到文件末尾

    • 获取 infile 中的总字节数(字符)

    • 将文件位置指示器倒回起点 (因为我们将再次阅读它)

  3. 声明一个 char 数组,大小为 - infile 中的所有计数字符 + 1 for '\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;

}

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2014-07-01
    相关资源
    最近更新 更多