C 利用管道将文件复制到其他目标,返回垃圾值
我在基于linux的环境中使用C,该环境利用系统调用、管道、fork等。 我可以将文件复制到一个单独的目的地,但有时会在输出文件中添加垃圾值,我无法理解是什么触发了问题,以及为什么会发生 这是代码强>C 利用管道将文件复制到其他目标,返回垃圾值,c,linux,operating-system,system-calls,C,Linux,Operating System,System Calls,我在基于linux的环境中使用C,该环境利用系统调用、管道、fork等。 我可以将文件复制到一个单独的目的地,但有时会在输出文件中添加垃圾值,我无法理解是什么触发了问题,以及为什么会发生 这是代码 #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<string.h> #include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
//defining the buffer size
#define SIZE_OF_BUFFER 50
int main(int argc, char *argv[]) {
int fpipe[2];
pid_t child_id;
//buffer to read the input file
char readBuffer[SIZE_OF_BUFFER];
//creating a pipe
pipe(fpipe);
//checking for valid number of parameters entered
if (argc != 3) {
printf("ERROR: Enter 2 parameters only.\n");
exit(1);
}
//Source file received as argument 1
int sourceFile = open(argv[1], 0);
//Destination file received as argument 2,if file does not exist it will create one
int destinationFile = open(argv[2], O_RDWR | O_CREAT | O_APPEND, 0666);
//check if file is able to open or not
if (sourceFile == -1 || destinationFile == -1) {
printf("ERROR: Couldnt open file\n");
exit(1);
}
//fork the child
child_id = fork();
if (child_id == 0) {
// inside the child prcocess
close(fpipe[1]);
while (read(fpipe[0], readBuffer, sizeof(readBuffer)) > 0) {
// Writing to the destination file from pipe
write(destinationFile, readBuffer, strlen(readBuffer) - 1);
}
close(fpipe[0]);
close(destinationFile);
} else {
// inside the parent process
close(fpipe[0]);
// code to read from a text file and store in pipe
while (read(sourceFile, readBuffer, sizeof(readBuffer)) > 0) {
write(fpipe[1], readBuffer, sizeof(readBuffer));
memset(readBuffer, 0, SIZE_OF_BUFFER);
}
close(fpipe[1]);
close(sourceFile);
wait(NULL);
}
}
其中,inputfile
是您创建的文件,您希望看到该文件被复制到输出文件中。
共有3个参数
感谢您的帮助。家长总是在写
sizeof(readBuffer)
,即使您的阅读量小于此值。检查读取的字节数,只写入那么多。strlen
不是一个好方法。空终止符何时写入?(从来没有)。检查read返回的值,而不是假设数据是正确以null结尾的字符串。(是否假设数据不包含任何空字节?)检查代码,查看所有使用strlen()或其他需要以NUL结尾的字符数组的库调用的地方,并确保始终满足该条件。然后再检查一遍,确保诸如read()之类的系统调用的返回得到完全正确的处理。
./a.out inputfile.txt outputfile.txt