C,unix并用write(),open()和lseek()覆盖一个char

Pyg*_*gar 4 c file seek

我需要用'?'替换文本文件中的字符.它没有按预期工作.

该文件的内容为'abc'(没有引号),我必须使用unix系统调用:lseek(),open()和write().我不能使用标准的C文件I/O功能.

该计划最终将其扩展为更广泛的"查找和替换"实用程序.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(){

int file = open("data", O_RDWR); //open file with contents 'abc'
lseek(file,0,0); //positions at first char at beginnging of file. 
char buffer;
read(file,&buffer, sizeof(buffer));
printf("%c\n", buffer); // text file containing 'abc', it prints 'a'. 

if (buffer == 'a'){
    char copy = '?';
    write(file,&copy,1); //text file containing 'abc' puts '?' were 'b' is.
    }

close(file);
}
Run Code Online (Sandbox Code Playgroud)

文件"data"包含abc,我想替换一个制作它?bc但是我得到了?c

read()正在读取正确的char,但write()正在写入下一个char.为什么是这样?

一直在谷歌搜索几个小时.

谢谢

tor*_*rek 5

答案实际上是以某种方式嵌入到您自己的代码中.

lseek您不需要立即执行的调用,open因为当您第open一个文件时,当前搜索偏移量为零.

在每次成功readwrite操作之后,搜索偏移量向前移动读取/写入的字节数.(如果你添加O_APPEND到你open的搜索偏移量也会每次写入之前移动到当前文件结束,但此时不相关.)

由于您成功完成了read一个字节,因此您的搜索偏移量从0变为1.如果要将其重新置于0,则必须手动执行此操作.

(当然,您还应该检查每个操作是否成功,但我认为您在此处为此简洁了.)