我不能让fread()将文件内容打印到字符串变量

时间:2014-10-09 01:08:50

标签: c fread

我一直在努力弄清楚如何让程序从文件中读取文本。我尝试过使用fgets()和循环的解决方案。程序运行但不打印变量,表示文本未被提取。

    #include <stdio.h>
    #include <string.h>
    #include "stdfn.h"


    int main(int argc, char* argv[])
    {
        char* request;
        char bf_text[1024];
        char character;

        intro("Site Blocker", 2014, "MIT");

        request = bash("curl http://redsec.ru/blocked_sites.txt"); // Source of bash() is at line 139 https://github.com/Pavelovich/lib-c/blob/master/stdfn.h
        //printf("%s", request);

        FILE* block_file = fopen(".blocked_sites", "w+"); // Changed from "w" based on this thread, currently only outputs a small part of the file.
        FILE* hosts = fopen("hosts", "w");
        FILE* hosts_tmp = fopen(".hosts", "w");

        // Print the text of the web request to the temporary
        // .blocked_sites file
        fprintf(block_file, "%s", request);

        rewind(block_file);
        fread(bf_text, sizeof(block_file), 1, block_file);
        printf("%s", bf_text);

        fclose(block_file);
        return 0;
    }

2 个答案:

答案 0 :(得分:3)

sizeof(block_file)没有给出文件的大小。它会给你一个文件指针的大小,可能是四个或八个字节。在你的情况下可能只有八个,因为你说它正在读取"74.125.2",这是八个字节,然后变得混乱。您需要在POSIX系统上使用类似stat()的内容,或fseek()ftell()的组合。

如果您要使用fread()fwrite(),您还应该以二进制模式打开文件,因为它们是二进制文件IO函数。它在UNIX系统上没有什么区别,但它可能在Windows上也是如此。因此,您不应该以您拥有的方式混合文本和二进制模式IO功能。

您还应该检查fopen()来电的回复,以确保它们成功。

您使用的bash()功能也完全被破坏了。每次调用时都会出现内存泄漏,因为它永远不会free() output,并且它会产生与您sizeof相同的free(request)错误,尽管它仍然会因为循环它。它只会浪费它分配的所有内存。并且正在泄漏内存,因为你永远不会#include。而且,除非您希望在整个地方出现多个定义错误,否则最好不要在malloc()多个翻译单元中进行{{1}}。事实上,整个“库”充满了男生型错误,包括重复检查{{1}}的返回失败,分配内存以适应指针而不是它指向的东西,依此类推。

答案 1 :(得分:1)

您正在为“只写”打开block_file。尝试将mode参数更改为“w +”,即     FILE block_file = fopen(“。blocked_sites”,“w +”); 如果您想打开现有文件而不是每次都创建一个新文件,请使用“r +”或“a +”代替“w +”。