Find the answer to your Linux question:
Results 1 to 4 of 4
hi, I have written a C code for writing a temporary file using function tmpfile() . I write 10 integers starting from -10. it goes like this: Code: #include <stdio.h> ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Jun 2011
    Location
    dallas ,texas
    Posts
    18

    tmpfile write and read


    hi,
    I have written a C code for writing a temporary file using function tmpfile() . I write 10 integers starting from -10. it goes like this:
    Code:
     #include <stdio.h>
      #include  <stdlib.h>
        
       int main()
       {
         int i;
         int arr[10];
         FILE *fp=NULL;
         fp = tmpfile();  // return the pointer to file
         if (fp==NULL) 
         {
         printf("file opening error");
         exit(1);
         }
         
         for (i=-20;i<10;i++)
          {
            arr[i] = i; // fill the array
          }
          fwrite(&arr,sizeof(int),10,fp);
          fclose(fp);
          return 0;
       }
    I have following questions
    1) when i examine the /tmp folder, i do not see any file.Is this because with tmpfile(), i do not have a filename? or is it because file is deleted when program terminates?
    2) In any case, if i want to read what i have just written, how do i do that. if i write another c code, where i would want to use fread, but i would need acess to original file, whose name i do not have.so, i am confused.
    3) so, overall, what is the use of creating such temporary file?

    thanks all

  2. #2
    Just Joined!
    Join Date
    Apr 2011
    Posts
    19
    According to the man page for tmpfile as soon as the file is closed (or program termination) the file is deleted. I suspect the normal usage of tmpfile is to write some data to the file and then use rewind or fseek to reposition the file pointer and then read the data back with fread. I've never used tmpfile, but the file is probably opened r/w so you can call fread after you have written some stuff after repositioning the file pointer.

  3. #3
    Just Joined!
    Join Date
    Jun 2011
    Location
    dallas ,texas
    Posts
    18
    do you mean that i write something into temp file, re position the file pointer , and within same program, use fread to read it from that point. creating another program for reading would not work then, as there would not be access to the file name?

  4. #4
    Just Joined!
    Join Date
    Apr 2011
    Posts
    19

    I think you are looking for mkstemp

    which creates a unique file name, not a tmp file to be used only for the exclusive use of a single program. mkstemp's file name would then be used to create a tmp file which you would have control over as to when it would be deleted.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •