c中的文件反向复制

File reversing copy in c

我正在尝试完成一个可以派生子进程的程序,父进程可以获取输入文件(在同一目录下),反转该文件的内容,然后使用管道函数传递给子进程。 Child 将从管道读取消息并生成输出文件。我已经完成了 fork、create pipe 和 reverse 功能。但是我被困在把它写到管道上。我知道当我尝试将参数传递给写入函数时肯定存在一些类型混淆,任何命中将不胜感激。

这是我目前的代码:

#include <stdio.h>
#include <stdlib.h> //exit
#include <string.h>
#include <sys/types.h>  //pid_t

#define READ_END 0
#define WRITE_END 1

int main(int argc, char *argv[]){

long loc;
FILE *in, *out;
char ch;

if (argc != 3)
{
    printf("Usage %s message\n", argv[0]);
    exit(EXIT_FAILURE);
}
int pipefd[2];
int pipe_return = pipe(pipefd);

if((in = fopen(argv[1], "rb")) == NULL) {
        printf("Cannot open input file.\n");
        exit(1);
}

if((out = fopen(argv[2], "wb"))==NULL) {
        printf("Cannot open output file.\n");
        exit(1);
}

if(pipe_return == -1)
{
    printf("Unable to create pipe\n");
    exit(EXIT_FAILURE);
}

pid_t return_from_fork = fork();

if (return_from_fork == -1)
{
    printf("Unable to fork\n");
    exit(EXIT_FAILURE);
}

else if (return_from_fork == 0) //this is a child
{
    char msg;
    close(pipefd[WRITE_END]);
    int read_return = read(pipefd[READ_END], &msg, 1);
    printf("read return:%d\n", read_return);
    while(read_return > 0){
        fputc(ch, out);
        printf("%c",msg);
        read_return = read(pipefd[READ_END], &msg, 1);
    }
    printf("child ends\n");
    close(pipefd[READ_END]);
    exit(EXIT_SUCCESS);
}

else if (return_from_fork > 0)
{
    close(pipefd[READ_END]);
    printf("this is parent\n");
    fseek(in, 0L, SEEK_END);
    loc = ftell(in);        
    while(loc >= 0L){
        fseek(in, loc, SEEK_SET);
        ch = fgetc(in);
        printf("%c",ch);
        int write_r = write(pipefd[WRITE_END], ch, 1);//here is the problem the printf() return -1
        printf("%d",write_r);
        loc--;
    }
    printf("\n");   
    close(pipefd[WRITE_END]);
    wait(NULL);
    printf("file successful generated.\n");
    fcloseall();
    exit(EXIT_SUCCESS);
}

}

编译结果如下:

zzz@ubuntu:~/Desktop/test$ gcc filereversecopy.c -o run
zzz@ubuntu:~/Desktop/test$ ./run src.txt out.txt
this is parent
�-1
-1e-1c-1n-1e-1t-1n-1e-1s-1 -1a-1 -1s-1i-1 -1s-1i-1h-1T-1
read return:0
child ends
file successful generated.
zzz@ubuntu:~/Desktop/test$ 

在你说的那一行是你传递 ch 来写的问题,ch 是 char 类型。我确定您的意思是 &ch 。我敢打赌,如果你改变写将 return 1 而不是 -1.

还有,你是找到底开始阅读,但是当你找到底时,你指向了EOF。您需要从 EOF 之前的位置开始阅读。所以在 "fseek(in, 0L, SEEK_END); loc = ftell(in);" 之后添加 "loc--; fseek(in, loc, SEEK_SET);" 使其工作。