小编Seb*_*iva的帖子

系统调用"open()"中的O_TRUNC实际上没有删除文件内容

根据我的理解,函数的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 …
Run Code Online (Sandbox Code Playgroud)

c unix system-calls

3
推荐指数
1
解决办法
712
查看次数

标签 统计

c ×1

system-calls ×1

unix ×1