我正在尝试编写一个可以反转文件内容的程序。 因此,给输入文件提供内容“abc”,它应该创建一个内容为“cba”的文件。
不幸的是,它不起作用,我不明白为什么。
你能帮帮我吗? 感谢 编辑:我忘了提到这是学校作业 - 我们必须使用像lseek和open这样的函数 - 请不要认为我应该使用fgetc anfd其他函数:)#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
void reverse_file(char * in, char * out)
{
int infile, outfile;
infile = open(in, O_RDONLY);
outfile = open(out, O_WRONLY);
char buffer;
char end = EOF;
write(outfile, &end, sizeof(char));
do
{
// seek to the beginning of a file
read(infile, &buffer, sizeof(char));
// printf("the code of a character %d\n", buffer); // returns 10 instead of EOF
lseek(outfile, 0, SEEK_SET);
write(outfile, &buffer, sizeof(char));
} while (buffer != EOF);
close(outfile);
close(infile);
}
int main()
{
reverse_file("tt", "testoutput");
return 0;
}
答案 0 :(得分:2)
read
返回它读取的字节数。要在到达文件末尾时停止循环,请将条件更改为读取的返回值。
int read_ret;
do
{
// seek to the beginning of a file
read_ret = read(infile, &buffer, sizeof(char));
// printf("the code of a character %d\n", buffer); // returns 10 instead of EOF
lseek(outfile, 0, SEEK_SET);
write(outfile, &buffer, sizeof(char));
} while (read_ret > 0);
当读取到达文件末尾并返回零时,它不会设置* buffer。这就是你的循环永不停止的原因。
答案 1 :(得分:1)
您需要阅读以阅读整个输入文件,然后将其写出来。不要尝试用char做char,也不要使用lseek。
答案 2 :(得分:1)
您当前的代码(在文件结尾的测试错误之外)将生成一个char的文件,因为write
会覆盖当前位置的文件中存在的数据(除非它是最后,它会追加)。
实际上,要反转文件,您应该从最后开始阅读它。
struct stat instat;
int pos;
fstat(infile, &instat);
pos = instat.st_size - 1;
do
{
// seek backward in the input file, starting from the end
lseek(infile, SEEK_SET, pos);
read(infile, &buffer, sizeof(char));
write(outfile, &buffer, sizeof(char));
} while (pos-- > 0);
(使用char读取char对unix read
和write
系统调用非常缺乏,因此,作为第二步,您应该考虑使用C基元(fopen
,fread
,fwrite
),或使用unix系统调用进行一些缓冲的读写操作。)
见: