Seb*_*iva 3 c unix system-calls
根据我的理解,函数的O_TRUNC说明符open()应首先删除文件中的内容,然后开始编写.
相反,它正在做的就是让我覆盖文件中的内容.
我的问题是该文件包含ASCII '11',它应该做的是读取它并将其覆盖为'8',但文件最终为'81',因为它不会在写入之前删除整个内容.
代码的目标是读取文件中的数字,将其减3,然后仅使用系统调用将该数字放回文件中.
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char*argv[]){
int fp = open("file.txt", O_RDONLY);
char c1, c2, c3='\n';
read(fp, &c1, 1);
read(fp, &c2, 1);
close(fp);
fp = open("file.txt", O_TRUNC || O_WRONLY);
if (c2 == '\n')
c1 -= 3;
else {
if (c2 >= '0' && c2 <= '2' ) {
c1--;
c2 += 7;
}
else
c2 -= 3;
}
if (c1 != '0')
write(fp,&c1,1);
if (c2 != '\n')
write(fp,&c2,1);
write(fp,&c3,1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
O_TRUNC || O_WRONLY是一个逻辑 "或",几乎肯定会导致int值为1,这通常O_WRONLY是定义为.你想要与运算符按位 "或" |.请注意,它只是一个|字符:
fp = open("file.txt", O_TRUNC | O_WRONLY);
Run Code Online (Sandbox Code Playgroud)