temp=tmpfile() lose all its contents?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • learner007
    New Member
    • May 2012
    • 2

    #1

    temp=tmpfile() lose all its contents?

    Dear there,

    I wrote a simple all->unix ascii file converter on fly, see the comments below. I am using temp=tmpfile() to hold contents for later processing, but it seems lost later on.

    Code:
    /* FILE* file is assigned before calling this routing. 
    After calling this routine, 'file; is supposed to point to the temporary file stream 
    with processed content. However, I found later that file has no content at all.
    */
    
    /** 
     * simple text convert: convert all to Unix line ending
     * I use fgets() to read a line, which stops whenever \n (LF) is met. However, different line ending could be used:
     * DOS/Windows: CR LF
     * Unix: LF
     * MAC OS X: LF
     * MAC (prior to MAC OS X): CR
     * this convert is simple since it is only for use with fgets(), strtok(), and strtof()
     * strtok() will skip leading 'sep' when processing tokens, in this file sep=' \t,'; strtof() will
     * skip leading white space as specified by isspace(). Hence I replace CR LF with LF SPACE; and CR with LF.
     */
    void trimcarriage(){
      FILE* temp=tmpfile();//see p483 k.n.king
      int ch, chnext;
      while(ch=getc(file) != EOF){
        if (ch != '\r'){//straight copy
          putc(ch, temp);
        }else{
          putc('\n',temp);//replace it with \n
          if (chnext=getc(file) != '\n'){
    	ungetc(chnext, file);//put it (including EOF) back
          }//otherwise '\n' is not wrote into temp
        }
      }
      fclose(file);
      rewind(temp);
      file=temp;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Are temp and file both FILE* to the same file?

    If so, you have a problem because you cannot have two active FILE* to the same file.

    Comment

    • learner007
      New Member
      • May 2012
      • 2

      #3
      I found the mistake in the statement:
      ch=getc(file) != EOF
      which should be
      (ch=getc(file)) != EOF
      due to operator precedence.

      Comment

      Working...