tags:

views:

95

answers:

2

Hi guys

I'd like to eliminate the extra '\n' at the end of a txt file. Which function can be used to do this job in c / c++.

Thanks advanced

A: 

One approach would be to iterate of the file line-by-line using getline, saving off that data for later. After each line is read, write the previous line (with \n). When no more data is available write the final line without the \n anymore.

Alternately seek to the end to get the size, read the data in blocks of some chunk size, rewriting them until the second-to-last character. If the last character is a \n don't write it, otherwise do write it.

Mark B
A: 

The posix way to do this is the truncate function. If you get the length of the file using seek or another OS call you can use truncate to trim the last char of the length of the file without rewriting the whole thing.

//This RESIZES the file without the need to REWRITE the whole thing:
struct stat fileStat;
stat("Filename", &fileStat); 
status = truncate("Filename",fileStat.st_size-1);

The windows equivalent function is chsize however it requires opening a file first:

   // Open a file 
   if( _sopen_s( &fh, "data", _O_RDWR | _O_CREAT, _SH_DENYNO,
                 _S_IREAD | _S_IWRITE ) == 0 )
   {
      if( ( result = _chsize( fh, _filelength( fh ) -1 ) ) == 0 )
         printf( "Size successfully changed\n" );
      else
         printf( "Problem in changing the size\n" );
      _close( fh );
   }
NoMoreZealots