Mac中的C Write()错误

Ban*_*ana 0 c


我正试图在我的Macbook Air上的文本文件中写字符,但它似乎没有用.
我尝试通过Xcode和Terminal进行编译.

但结果是一样的:
文件描述:3
写()错误!

这是代码.

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

void Error_handling(char* message);

int main() {
    int fd;

    char buf[] = "Let's go! \n";

    fd = open("data.txt", O_CREAT|O_RDONLY|O_TRUNC);
    if (fd == -1)
        Error_handling("open() Error! \n");

    printf("File Descripter: %d \n", fd);

    if(write(fd, buf, sizeof(buf))==-1)
        Error_handling("write() Error! \n");

    close(fd);

    return 0;
}

void Error_handling(char* message)
{
    fputs(message, stderr);
    exit(1);
}
Run Code Online (Sandbox Code Playgroud)

fgh*_*ghj 5

你打开文件,O_RDONLY然后尝试写,当然它报告错误.

正如评论所暗示的那样,正确的开放变体应该是:

fd = open("data.txt", O_CREAT|O_WRONLY|O_TRUNC, 0600);
Run Code Online (Sandbox Code Playgroud)