【问题标题】:trouble to write in a file with dup2 and printf使用 dup2 和 printf 写入文件时遇到麻烦
【发布时间】:2025-12-17 17:30:03
【问题描述】:

我对这个简单的代码有疑问:

int main(int argc, char const *argv[]) {
  int fichier = open("ecrire.txt", O_APPEND | O_WRONLY | O_CREAT);

  dup2(fichier, 1);

  printf("test");
  return 0;
}

我只需要用 dup2 和 printf 在我的文件上写“测试”。但没有任何内容附加到文件中。

如果您有解决方案,谢谢

【问题讨论】:

  • 贴出的代码编译失败!除其他外,它缺少所需的#include 语句:`#include #include #include ` 用于open() 函数,@ 987654325@函数:dup2()#include <stdio.h> 函数:`printf()
  • 在调用open()时,始终检查(0>=)返回值以确保操作成功。在调用dup2() 时,请始终检查返回值(!= -1)以确保操作成功。
  • 建议使用这种形式的open() 语句:int open(const char *pathname, int flags, mode_t mode); 以便可以读取生成的文件等

标签: c printf dup


【解决方案1】:

以下建议的代码

  1. 干净编译
  2. 执行所需的功能
  3. 正确检查错误
  4. 包含所需的#include 语句。

现在建议的代码:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

int main( void )
{
    int fichier = open("ecrire.txt", O_APPEND | O_WRONLY | O_CREAT, 0777);
    if( 0 > fichier )
    {
        perror( "open failed" );
        exit( EXIT_FAILURE );
    }

    // IMPLIED else, open successful

    if( dup2(fichier, 1) == -1 )
    {
        perror( "dup3 failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, dup2 successful

    printf("test");
    return 0;
}

在 linux 上这个命令:

ls -al ecrire.txt displays

-rwxrwxr-x 1 rkwill rkwill 4 Apr 19 18:46 ecrire.txt

这个浏览文件的内容:

less ecrire.txt 

结果:

test

【讨论】:

    【解决方案2】:

    您的示例确实可以使用适当的标头,但它授予文件权限,仅允许 root 用户在此程序创建文件后读取文件。所以我为用户添加了 rw 权限。我还删除了 O_APPEND 因为你说你不想追加:

    #include <unistd.h>
    #include <fcntl.h>
    #include <stdio.h>
    
    int main() {
      int fichier = open("ecrire.txt", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
    
      dup2(fichier, 1);
    
      printf("test");
      return 0;
    }
    

    【讨论】: