【问题标题】:Using O_CREAT O_WRONLY : How to get current position in the file and append data at the end?使用 O_CREAT O_WRONLY :如何获取文件中的当前位置并在末尾附加数据?
【发布时间】:2020-08-19 10:16:45
【问题描述】:

我想将数据从套接字读取到 FILE。如果 FILE 不存在,创建一个文件 ONLY ONCE 和来自客户端的任何后续数据,找到 FILE POINTER 的当前位置并追加最后的数据。

现在,每次我运行代码时都会创建一个新文件。

// Server is 'Ready' to read data from the socket :

// fd - declared as **static int**, to enable it bet'n the function calls


            fd = open("/home/regs_p/cprograms/tcp/RSA.c", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC);

              if (fd < 0) {

                printf("Some problem with the file!");

              }

            else {
            
                while ((b = read(sockfd, buffer, sizeof(buffer) - 1)) > 0) {

                    if (fd > 0 ) {

                        fp = fdopen(fd, "a+");

                        fwrite(buffer, sizeof(buffer), 1, fp);

                    //  fseek(fp, 0, SEEK_CUR);

                    }   

                    size = ftell(fp);
            
                }

            //  printf("Buffer = %s", buffer);

            }

【问题讨论】:

  • 使用O_APPEND。那么你根本不需要文件指针。
  • 使用FILE *fp = fopen(filename, "a"); 而不是open
  • @RobertoCaboni 然后丢掉fdopen() ...
  • fd = open("/home/regs_p/cprograms/tcp/RSA.c", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC); 不完整。创建文件时,您需要向open() 提供第三个mode_t 参数,例如fd = open("/home/regs_p/cprograms/tcp/RSA.c", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC, 0644);
  • @Andrew Henle - 是的,对。我忘记了“Umask”值。大约 12 年前,在我的 Unix 和 Shell 脚本编程课程中了解了“Umask”。谢谢提醒!

标签: c file sockets flags file-descriptor


【解决方案1】:

O_APPENDO_CREAT 一起使用将仅在文件不存在时创建文件。如果存在,则打开文件,文件指针默认位于末尾。

【讨论】:

  • 不应该是 O_WRONLY | O_APPEND?
  • @Ace.McCloud 是的,你是对的。 O_WRONLYO_RDONLYO_RDWR 之一对于每个 open() 呼叫都是必需的,所以我根本没有提及它。如果文件不存在并且您没有指定O_CREAT,则打开应该会失败。所以我想应该是:O_WRONLY | O_APPEND | O_CREAT
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-06
  • 2021-12-10
  • 2017-03-26
  • 1970-01-01
  • 2018-10-31
  • 2012-06-21
相关资源
最近更新 更多