gpt4 book ai didi

c - c中的文件逆向复制

转载 作者:行者123 更新时间:2023-11-30 15:16:24 26 4
gpt4 key购买 nike

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

这是我到目前为止的代码:

#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 。我敢打赌,如果你改变 write 将返回 1 而不是 -1。

此外,您查找到末尾以开始阅读,但是当您查找到末尾时,您指向的是 EOF。您需要从 EOF 之前的位置开始读取。所以在“fseek(in, 0L, SEEK_END); loc = ftell(in);”之后添加“loc--; fseek(in, loc, SEEK_SET);”让它发挥作用。

关于c - c中的文件逆向复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114086/

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