我试图运行将文本从一个文件复制到另一个文件的程序

im trying to run a program that copy the text from one file to the other

本文关键字:文件 一个 复制 程序 另一个 运行 文本      更新时间:2023-10-16

im试图编写一个程序,该程序获取两个文本文件,并将文本从一个文件复制到另一个文件。该函数似乎正在工作,但它更改了我写入的文件,而不是文本文件。

请帮助!!!!

int main(int argc, char *argv[]) {
    printf("Hello World!n"); 
    char* file1 = argv[1];
    char* file2 = argv[2];
    char buffer1[SIZE+1];
    //char buffer2[SIZE+1];
    int fd1, fd2;
    int run = 1;
    int run2;

    fd1 = open(file1, O_RDONLY);
    if(fd1 < 0){
        perror("after open ");   // checks if the file was open ok 
        exit(-1);   
    }
    fd2 = open(file2, O_RDWR );
        if(fd2 < 0){
        perror("after open ");   // checks if the file was open ok  
        exit(-1);
        }
    while(run != 0){
        run = read(fd1, buffer1, SIZE);     
        run2 = write(fd2, buffer1, SIZE);
        printf("run 2: %d", run2);
    }

    close(fd1);
    close(fd2);
    return 1;
}

可能是因为

 fd2 = open(file2, O_RDONLY);

仅读取文件 -> fd2

您的程序无法处理读取数量读取的情况小于缓冲区大小:

while(run != 0){
    run = read(fd1, buffer1, SIZE);     
    run2 = write(fd2, buffer1, SIZE);
    printf("run 2: %d", run2);
}

如果读取的金额小于大小,则将写垃圾到第二个文件。

为什么使用低级文件I/O?

这可以使用C语言函数高水平完成:

FILE * input;
FILE * output;
input = fopen("input_file.bin", "rb");
output = fopen("output_file.bin", "wb");
while (!feof(input))
{
  int quantity = fread(&buffer1[0], SIZE, 1, input);
  int bytes_written = fwrite(&buffer1[0], quantity, 1, output);
}

在上面的示例中,编写的字节数是读取的字节数。如果字节读取的数量小于 SIZE,则它将写入读取到输出文件的字节量化,而不再是。