调用系统UNIX - C中的文件复制

时间:2015-05-14 20:12:32

标签: c

我尝试创建源文件的副本,但目标文件始终为空。

算法是:从STDIN读取并写入源文件,然后读取该文件并将文本写入目标文件。

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

#define BUFFSIZE 8192

int main(){
    int fdsource, fdtarget;
    int n, nr;
    char buff[BUFFSIZE];

    fdsource = open("source.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); // Create and open a source file in read/write
    if (fdsource < 0){
        printf("Source file open error!\n");
        exit(1);
    }

    fdtarget = open("target.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); // Create and open a source file in write only
    if (fdtarget < 0){
        printf("Target file open error!\n");
        exit(1);
    }

    printf("\nInsert text:\n");
    while ((n = read(STDIN_FILENO, buff, BUFFSIZE)) > 0){ // Read from STDIN and write to source file
        if ((write(fdsource, buff, n)) != n){
            printf("Source file write error!\n");
            exit(1);
        }
    }

    while ((read(fdsource, buff, n)) > 0){ // Read from source file and write to target file
        if ((write(fdtarget, buff, n)) != n){
            printf("Source file open error!\n");
            exit(1);
        }
    }
    close(fdsource);
    close(fdtarget);
    exit(0);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您的代码存在问题&#34;您已在初始阶段打开了该文件&#34;。要解决此问题,只需在写入模式下打开源文件并写入所有数据,然后在读取模式下关闭并重新打开源文件,然后在写入模式下打开目标文件。 修改后的代码如下所示,未经过测试

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

#define BUFFSIZE 8192

int main(){
    int fdsource, fdtarget;
    int n;
    char buff[BUFFSIZE];

    fdsource = open("source.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); // Create and open a source file in read/write
    if (fdsource < 0){
        printf("Source file open error!\n");
        exit(1);
    }
    printf("\nInsert text:\n");
    while ((n = read(STDIN_FILENO, buff, BUFFSIZE)) > 0){ // Read from STDIN and write to source file
        if ((write(fdsource, buff, n)) != n){
            printf("Source file write error!\n");
            exit(1);
        }
    }

    close(fdsource);
    fdsource = open("source.txt", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); // Create and open a source file in read/write
    if (fdsource < 0){
        printf("Source file open error!\n");
        exit(1);
    }

    fdtarget = open("target.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); // Create and open a source file in write only
    if (fdtarget < 0){
        printf("Target file open error!\n");
        exit(1);
    }

    while ((read(fdsource, buff, n)) > 0){ // Read from source file and write to target file
        if ((write(fdtarget, buff, n)) != n){
            printf("Source file open error!\n");
            exit(1);
        }
    }
    close(fdsource);
    close(fdtarget);
    exit(0);
    return 0;
}

如果在任何地方出错,请使用上述逻辑。