gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:37:38 25 4
gpt4 key购买 nike

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

算法是:从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;
}

如果哪里有错,使用上面提到的逻辑。

关于调用系统 UNIX - C 中的文件复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com