使用O_CREAT O_WRONLY:如何获取文件中的当前位置并在末尾附加数据?

问题描述

我想从套接字读取数据到 FILE 。如果 FILE 不存在,请创建文件 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,SEEK_CUR);

                    }   

                    size = ftell(fp);
            
                }

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

            }

解决方法

仅将O_APPENDO_CREAT一起使用才创建文件。如果存在,默认情况下将打开文件,并且文件指针将位于末尾。