Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to store the pgm file open into buffer using "strcat"

Status
Not open for further replies.

Silentkiller

Technical User
Feb 13, 2003
14
GB
Hi,
I need some help with storing the Data of Pgm file into Buffer using Strcat;
Here is my source code:

/* fread example: read a complete file */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
FILE * pFile;
long lSize;
char * buffer;
char filename[80];
int ch;
int type;
int i;
printf(&quot;Please enter the file name : &quot;);
scanf(&quot;%s&quot;, &filename);

pFile = fopen (filename, &quot;r&quot; );
if (pFile==NULL) exit (1);


ch = getc(pFile);
if (ch != 'P')
{
printf(&quot;ERROR(1) : Not Valid PGM File type\n&quot;);
exit(1);
}

printf(&quot;\n The filename is %s&quot;, filename);

ch = getc(pFile);
type = ch - 48;
if (( type != 2) && ( type != 5))
{
printf(&quot;EORROR(2): Not Valid PGM File type\n&quot;);
}

printf(&quot;\n The value is %ld\n&quot;, type);

// obtain file size.
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);

// allocate memory to contain the whole file.
buffer = (char*) malloc (lSize);
if (buffer == NULL) exit (2);

printf(&quot;\n The Filesize = %ld\n &quot;, lSize);
// copy the file into the buffer.
for (i=0; i<lSize; i++)
{
strcat(buffer, filename);
}
/*** the whole file is loaded in the buffer. ***/

// terminate
fclose (pFile);

return 0;
}

your help will be greatly appreciated
 
PGM - portable graymap file format (apparently).

Anyway, it really doesn't matter what type of file it is... If you just want to put the whole thing into a string using stream I/O routines, you can do it like this...
Code:
  rewind (pFile);

  // allocate memory to contain the whole file.
  buffer = (char*) malloc (lSize+1);
  if (buffer == NULL){
    printf(&quot;Error: Not Enough memory.\n&quot;);
    exit (1);
  }

  // The source and destination strings for
strcat()
Code:
  // must be null-terminated, so we do this to
buffer
Code:
  // and the same for
readCharacter
Code:
  buffer[0] = 0;

  char readCharacter[2];  // Latest read character
  readCharacter[1]= 0;    // .. and a NULL character

  // Now add characters to the string until
  // the end of the file is reached

  while(!feof( pFile ))
  {
    readCharacter[0] = getc(pFile);
    strcat(buffer, readCharacter);
  }

  // Close the file
  fclose (pFile);

  // ...
  //  Do interesting stuff with the
buffer
Code:
 string
  // ...

  // Free the allocated memory for
buffer
Code:
  free(buffer);

Hope it helps you,
Stephen
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top