c - 打开时出现段错误

标签 c file file-io segmentation-fault

我是 C 文件管理新手。我的老师想要创建一个从源文件复制到目标文件的函数作为作业。我创建了,但它总是给我错误:段错误。

void source_to_destination(FILE *source , FILE *destination)
{
    char name_source[10], name_destination[10],line[100];
    memset(line,0,sizeof(line));
    memset(name_source,0,sizeof(name_source));
    memset(name_destination,0,sizeof(name_destination));
    read_name_file(name_source);
    read_name_file(name_destination);

    source = fopen(name_source,"r");
    destination = fopen(name_destination,"w");

    while(fgets(line,sizeof(line),source) != NULL)
    {
        fputs(line,destination);
    }

}

最佳答案

将数据从一个文件复制到另一个文件时,首选以二进制方式读写。使用面向行的输入函数(例如 fgetsgetline)读取无法正确读取文件中的所有字符有多种原因。文本输出函数也有类似的缺点(例如,尝试写入可打印范围之外的字符或具有 ASCII 替代含义的字符)

使用freadfwrite以二进制模式读取和写入文件并不比使用fgetsfputs更困难。但是,使用 freadfwrite 可以避免在文本模式下尝试进行常规文件复制所固有的陷阱,从而保证您获得正确且准确的数据副本。

如果您知道源文件中除了文本之外什么都没有,那么以文本模式复制它就没有问题。这只是意味着您必须编写另一个函数来处理非文本文件。 (通常您不会看到基于文件内容的不同复制例程)。以二进制方式读取和写入消除了所有这些考虑因素。

下面是一个 filecopy 函数的简短示例,该函数会将文件中的所有字节读入缓冲区,然后将缓冲区的内容写入目标文件。 (缓冲读/写通常效率更高,您可以通过调整 MAXS 轻松调整缓冲区大小)该函数返回成功时复制的字节数,-1否则。请仔细查看,如果有任何问题请告诉我:

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

#define MAXS 256

int filecopy (char *source, char *dest);

int main (int argc, char **argv) {

    if (argc < 3) { /* validate 2 arguments given */
        fprintf (stderr, "usage: %s file1 file2\n", argv[0]);
        return 1;
    }

    int filesize = 0;

    if ((filesize = filecopy (argv[1], argv[2])) == -1) {
        fprintf (stderr, "error: filecopy failed.\n");
        return 1;
    }

    printf ("\n copied '%s' -> '%s' ('%d' bytes)\n\n", 
            argv[1], argv[2], filesize);

    return 0;
}

int filecopy (char *source, char *dest)
{
    char *buf = NULL;   /* buffer used to read MAXS bytes from file */
    size_t nbytes = 0;  /* number of bytes read from file */
    size_t idx = 0;     /* file index (length)            */
    FILE *fp = fopen (source, "r"); /* stream pointer     */

    if (!fp) {  /* open source for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", source);
        return -1;
    }

    /* allocate MAXS size read buf initially */
    if (!(buf = calloc (MAXS, sizeof *buf))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return -1;
    }

    /* while data read MAXS *buf from file - realloc for next read */
    while ((nbytes = fread (buf+idx, sizeof *buf, MAXS, fp))) 
    {
        idx += nbytes;              /* update total bytes read */
        if (nbytes < MAXS) break;   /* end-of-file reached */

        /* full read - realloc for next   */
        void *tmp;
        if (!(tmp = realloc (buf, (idx + nbytes) * sizeof *buf))) {
            fprintf (stderr, "error: virtual memory exhausted.\n");
            exit (EXIT_FAILURE);
        }
        buf = tmp;
    }
    fclose (fp);    /* close input stream   */

    if (!(fp = fopen (dest, "w+b"))) { /* open output stream */
        fprintf (stderr, "error: file open failed '%s'.\n", dest);
        exit (EXIT_FAILURE);
    }
    fwrite (buf, sizeof *buf, idx, fp);
    fclose (fp);    /* close output stream  */

    free (buf);
    return (int)idx;
}

编译

gcc -Wall -Wextra -O3 -o bin/filecopy_simple filecopy_simple.c

输入文件(二进制)

-rw-r--r--  1 david david  66672 Nov 19 13:17 acarsout2.bin

使用/输出

$ ./bin/filecopy_simple dat/acarsout2.bin dat/acarsout3.bin

 copied 'dat/acarsout2.bin' -> 'dat/acarsout3.bin' ('66672' bytes)

验证

$ ls -al acarsout[23]*
-rw-r--r--  1 david david  66672 Nov 19 13:17 acarsout2.bin
-rw-r--r--  1 david david  66672 Dec 13 14:51 acarsout3.bin

$ diff dat/acarsout2.bin dat/acarsout3.bin
$

关于c - 打开时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34254722/

相关文章:

c - 指针无缘无故变为空

Javascript/AJAX/使用 JSON 发送到服务器文本和文件

java - .delete() 的冗余使用

java - 为什么 File#delete 在文件未被删除时没有抛出异常?

c - 使用 C 函数 fopen、fread 和 fwrite 与串行端口交互?

C 突然弄乱了二维数组中的值

c - 具有指针标记结构的 malloc

c - 为什么 gcc 不优化全局变量?

file - 无法将文件导入 Rust 中的另一个文件

从R中的固定宽度文件读取矩阵