首页 > 解决方案 > 如何在 Linux 中使用 C 语言使用“写入”系统调用?

问题描述

我的代码工作正常。我得到的唯一错误是在程序将文本写入文件即 text1.txt 后,当我实际打开它时,文本文件会打印一些奇怪的符号,如 /00。

int fd;
fd = open("text1.txt", O_RDWR);
char text[] = "This is my file.";
write(fd,text,sizeof(text));

标签: clinux

解决方案


  • 您需要确保open成功而不是盲目地写入文件描述符。
    • 始终检查系统调用(和大多数 C 标准库函数)errno的返回值,并检查返回值是否指示错误。
  • 您的字符串文字将在点后包含一个隐藏的\0( NULL)字符。
    • 因此,直接写入text文件将包括\0您所看到的尾随。

这些问题可以通过以下方式纠正:

  • 始终检查系统调用的返回值 - 在这种情况下:将有用的错误消息打印到标准输出并执行任何必要的清理(goto closeFile;语句)。

    • 因为 C 没有本机try/catch或 RAII,这意味着很难编写简洁的错误处理和清理代码,但在 C 中通常可以接受goto用于常见的清理代码,因此声明。goto closeFile
  • 用于strlen获取字符串的实际长度。

    • 尽管在紧要关头,sizeof(text) - 1只要您处于 C 编译器知道的长度的范围内,如果由于数组指针衰减而text越过函数边界,使用sizeof()将不起作用。

像这样:

void writeToFile() {

    int fd = open( "text1.txt", O_CREAT | O_WRONLY ); // Use `O_WRONLY` instead of `O_RDWR` if you're only writing to the file. Use `O_CREAT` to create a file if it doesn't already exist.
    if( fd == -1 ) {
        printf( "Error opening file: errno: %d - %s\n", errno, strerror( errno ) );
        return;
    }

    size_t textLength = strlen( text );
    size_t written = write( fd, text, textLength );
    if( written == -1 ) {
        printf( "Error writing text: errno: %d - %s\n", errno, strerror( errno ) );
        goto closeFile;
    }
    else if( written < textLength ) {
        printf( "Warning: Only %d of %d bytes were written.", written, textLength );
        goto closeFile;
    }
    else {
        // Carry on as normal.
    } 

closeFile:
    if( close( fd ) == -1 ) {
        printf( "Error closing file: errno: %d - %s\n", errno, strerror( errno ) );
    }
}

推荐阅读