Thread: read write to file

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    58

    Question read write to file

    Hi,
    How can I erase the data stored in /tmp/a.txt after every run of this code?

    Code:
    #include <stdio.h>      // IO operations
    #include <unistd.h>       //for pid, ppid, fork functions
    #include <sys/types.h>  //for pid_t type, kill function
    #include <stdlib.h>     //for exit function
    #include <signal.h>    //for kill function
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <string.h>
    #include <fcntl.h>
    #include <unistd.h>
    #include <assert.h>
    #include <error.h>
    
    int main()
    {
     int fd;
     pid_t x=fork();
     char bufferSize[80];
     char buffer[]="Wellcome to Linux Embedded";
     char bufferNull[]=" ";
     fd=open("/tmp/a.txt", O_RDWR | O_CREAT ,0777);
     //printf("fd=%d\n",fd);
     if(fd==-1)
     {
     printf("can't open file\n");
     }
     
     if(x>0)
     {
        read (fd, bufferSize, sizeof(bufferSize));
        printf("reading to file\n");
      
       write (fd, buffer, strlen(buffer));
       printf("writing to file\n");
       
     }
    
     close (fd) ;// Close the file descriptor
     return 0;
     }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    If you want to physically remove the file from storage:
    remove - Stdio.h - C - C++ Computing Reference with Worked Examples

    If you want to delete the contents, you can overwrite it with this:

    Code:
    FILE *file;
    if ((file = fopen("/tmp/a.txt", "w")) != NULL) 
      fclose(file);
    I really don't know how that translates to file descriptors. That is a pretty old API, are you sure you need to use it?

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    If you need a temporary file I suggest using tmpfile(). After closing the file or exiting the program, the file will be removed automatically.

    Bye, Andreas

  4. #4
    Registered User
    Join Date
    Feb 2013
    Posts
    58
    thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 19
    Last Post: 01-04-2013, 11:20 PM
  2. Replies: 2
    Last Post: 01-02-2013, 11:03 PM
  3. Replies: 12
    Last Post: 06-18-2012, 08:23 AM
  4. read and write to file
    By rahulsk1947 in forum C++ Programming
    Replies: 2
    Last Post: 06-03-2007, 09:56 PM
  5. File Read/write
    By krsauls in forum C Programming
    Replies: 5
    Last Post: 05-01-2007, 09:16 PM