Использование каналов для копирования файла в другое место назначения, возвращая значения мусора - PullRequest
0 голосов
/ 29 октября 2019

Я использую C в среде на основе linux, в которой используются системные вызовы, каналы, разветвление и т. Д. Я могу скопировать файл в отдельное место назначения, но у меня иногда появляются значения мусора добавлено в выходной файл, и я не могу понять, что вызывает проблему и почему это происходит.

Вот код!

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

Как запустить: Скомпилируйте в терминале и запустите с

./a.out inputfile.txt outputfile.txt

, где inputfile - это файл, который вы создали, который вы хотели бы видеть скопированным в выходной файл. Всего 3 аргумента.

Спасибо за любую помощь.

...