LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   wrong with fprintf (https://www.linuxquestions.org/questions/programming-9/wrong-with-fprintf-18002/)

whepin 04-08-2002 06:11 AM

wrong with fprintf
 
char buf[2048];
int i=1;

fin=fopen(argv[1],"r");
fout=fdopen(1,"w");
memset(buf,0,sizeof(buf));
while(fread(buf,sizeof(char),2047,fin)>0)
{
buf[strlen(buf)-1]=0;
fprintf(fout,"ret times=%d,%s\n",i++,buf);
}

The above is part of my program.
I just only want to read the file argv[1] and write to the console,but the output tell me:
If the specified file is smaller than 2047bytes,It works fine.But if larger than 2047,the file then cannot written to the console completely.

So how should i do then?
Thanks for help.

crabboy 04-08-2002 10:20 PM

One question for you:

Why do you have this line in your program?
Code:

buf[strlen(buf)-1]=0;
Figure out your problem yet?

Since what you read isn't a null terminated string, you are trying to NULL terminate it. The problem is you are using strlen on a non string... Grab the length of the string you read and tack the NULL on after that.


Code:

#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 2047

main(int argc, char * argv[])
{
  char buf[BUFFER_SIZE + 1];
  int i=1;
  FILE * fin;
  FILE * fout;
  int iRead = 0;

  fin = fopen( argv[1], "r" );
  fout = fdopen( 1, "w" );
  memset( buf, 0, sizeof( buf ));
  while(( iRead = ( fread( buf, sizeof( char ), BUFFER_SIZE, fin))) > 0 )
  {
      buf[ iRead ] = 0;
      fprintf( fout,"ret times=%d, iRead = %d, [%s]\n", i++, iRead, buf);
  }

}



All times are GMT -5. The time now is 02:11 PM.