复制文件时出现分段错误

时间:2012-01-22 12:14:58

标签: c fread printf file-copying

我是初学者,我正在尝试将大小约33MB(精确到33136KB)的非常大的文本文件的内容复制到新文件中。我在运行程序时遇到分段错误。只有16KB被复制到我的新文件中。 我要复制的文件名是“test_file3”,我的新文件名是“newfile”。我在CentOS-5的虚拟盒子里做了这一切。 以下是详细信息:

[root@localhost decomp_trials]# cat read_file.c

    #include <stdio.h>
    #include <stdlib.h>

    int main( int argc, char *argv [] )
    {
            FILE *ifp, *ofp;
            char *ptr;

            ifp = fopen ( argv [ 1 ], "r" );
            ofp = fopen ( argv [ 2 ], "a" );

            for (  ptr = malloc ( 10 ); fread ( ptr, 1, 10, ifp ); )
                    fprintf ( ofp, ptr );

            fclose ( ifp );
            fclose ( ofp );

            return 0;
    }

[root@localhost decomp_trials]# cc read_file.c -o read_file
[root@localhost decomp_trials]# ./read_file /root/sys_cl_huk_ajh/imp/copy_hook7/test_file3 newfile
Segmentation fault
[root@localhost decomp_trials]# du -s newfile 
16      newfile
[root@localhost decomp_trials]# pwd
/root/sys_cl_huk_ajh/pro_jnk/decomp_trials
[root@localhost decomp_trials]# du -s ../../imp/copy_hook7/test_file3
33136   ../../imp/copy_hook7/test_file3
[root@localhost decomp_trials]# 

请告诉我我可能做错了什么。有没有更好的方法?请帮帮我

1 个答案:

答案 0 :(得分:2)

不要使用fprintf;它将其第二个参数视为格式字符串。使用fwrite

至于为什么它会出现错误,请考虑如果您的输入数据恰好包含例如%s。然后fprintf将开始遍历堆栈,读取随机数据,直到找到0值字节(空终止符)。这很容易导致进入不属于应用程序的内存。

相关问题