簡體   English   中英

調用系統UNIX - C中的文件復制

[英]Call system UNIX - File copy in 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;
}

您的代碼的問題是“您已在初始階段打開了該文件”。 要解決此問題,只需在寫入模式下打開源文件並寫入所有數據,然后在讀取模式下關閉並重新打開源文件,然后在寫入模式下打開目標文件。 修改后的代碼如下所示,未經過測試

#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;
}

如果錯在任何地方使用上面提到的邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM