【问题标题】:I wrote an function which reads in an entire file into a string but it doesnt work我写了一个函数,它将整个文件读入一个字符串,但它不起作用
【发布时间】:2020-05-27 21:17:00
【问题描述】:

所以,我需要将整个文件读入 c 中的字符串,我不知道文件会有多大。我写了这个函数,但它不起作用:

int slurp(char * filepath, char * outputfile) {  
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        outputfile = (char *) calloc(ftell(fp) + 1, sizeof(char));
        fread(outputfile, ftell(fp), sizeof(char), fp);
        fseek(fp, 0, SEEK_SET);
        outputfile[ftell(fp)] = '\0';
    }
    return success;
}

打开文件没有报错,但是当我打印输出文件时,我只得到(null)。

为什么它不起作用? 谢谢。

我试过你的建议还是不行:

int slurp(char * filepath, char * outputfile) {
    fp = fopen(filepath, "r");
    int success = 0;
    if (fp == NULL) {
        success = 1;
    }
    if (success == 0) {
        fseek(fp, 0, SEEK_END);
        size_of_file = ftell(fp);
        fseek(fp, 0, SEEK_SET);
        outputfile = (char *) calloc(size_of_file + 1, sizeof(char));
        fread(outputfile, size_of_file, sizeof(char), fp);
        outputfile[size_of_file] = '\0';
    }
    return success;
}

【问题讨论】:

  • 您需要在阅读内容之前回到开头
  • " 我不知道文件会有多大' --> 如果文件大于LONG_MAXlong ftell(FILE *) 开始限制。但我怀疑 OP 是否关心大文件。
  • 旁白:没有理由打电话给ftell(fp) 3x。一次应该就够了。更好的是,对于最终的 outputfile[n] = '\0';,使用来自 size_t n = fread() 的返回值。
  • 我编辑了问题,有编辑过的代码,但还是不行
  • 也许fp = fopen(filepath, "rb");

标签: c string io


【解决方案1】:

阅读前先从头开始(与此相反):

fseek(fp, 0, SEEK_SET);
fread(outputfile, ftell(fp), sizeof(char), fp);

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 2021-05-26
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2012-10-21
    • 2016-10-12
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多