0

我正在尝试使用 Linux 中的 C 编程从资源文件中追加到现有文件。但是,我的代码对此不起作用,any1 可以告诉我代码有什么问题以及 O_APPEND 是如何工作的吗?谢谢 :)

char ifile[150];
char tfile[150];
char cc;

system("clear");
printf("Please enter your resource file name : ");
gets(ifile);
printf("Please enter your destination file name : ");
gets(tfile);

int in, out;

in = open(ifile, O_RDONLY);
int size = lseek(in,0L,SEEK_END);
out = open(tfile, O_WRONLY |O_APPEND);
char block[size];
int pdf;
while(read(in,&block,size) == size)
    pdf = write(out,&block,size);
close(in);close(out);
if(pdf != -1)
    printf("Successfully copy!");
else
    perror("Failed to append! Error : ");
printf("Press enter to exit...");
do
{
    cc = getchar();
} while(cc != '\n');
4

1 回答 1

1

这里的问题是您将读取光标移到文件末尾以了解其大小,但您不会倒退到文件的开头以便能够读取。所以read()读取EOF,然后返回0

int size = lseek(in, 0L, SEEK_END);
out = open(tfile, O_WRONLY | O_APPEND);

应该

int size = lseek(in, 0L, SEEK_END);
lseek(in, 0L, SEEK_SET);
out = open(tfile, O_WRONLY | O_APPEND);

另外,在读写时,应该使用blockand not &block,因为block已经是指针(或地址)。

哦,还有...当您打开文件out进行写入时...如果文件不存在,它将失败。

这里如何使用权限设置为 644 创建它:

out = open(tfile, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

(如果文件已经存在,这不会有任何影响)

于 2012-12-07T20:09:30.730 回答