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!

Is storing of Data Carried out? 1

Status
Not open for further replies.

Silentkiller

Technical User
Feb 13, 2003
14
GB
Hi,
i wrote a program to open and read a file and wanted to store my the content into a buffer. Does my program works? How can i read the data from my buffer?

#include <stdio.h>
#include <string.h>
#define buffer 1000
main()
{ FILE *pf;

int i;
int width;
int height;
int maxVal;
int type;
int data;
int size;
int ch;
char string[80];
char buff[buffer];

printf(&quot;Please enter Filename : &quot;);
scanf(&quot;%s&quot;, string);
if((pf=fopen(string, &quot;r&quot;)) == NULL)
{
printf(&quot;Error(1) : Invalid %s File\n&quot;, string);
exit(1);
}

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

ch = getc(pf);
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 P%ld&quot;, type);

while (getc(pf) != '\n');
while (getc(pf) == '#')
{
while(getc(pf) != '\n');
break;
}

fscanf(pf, &quot;%ld&quot;, &width);
fscanf(pf, &quot;%ld&quot;, &height);
fscanf(pf, &quot;%ld&quot;, &maxVal);

printf(&quot;\n Width = %d&quot;, width);
printf(&quot;\n Height = %d&quot;, height);
printf(&quot;\n MaxVal = %d\n&quot;, maxVal);
size = width*height;
while (getc(pf) != '\n');
for(i=0; i<=size; i++)
{
fscanf(pf,&quot;%ld&quot;,&data); // problem section
strcpy(buff,string); // problem section
printf(&quot;%ld&quot;, buff); // problem section
}
fclose(pf);
printf(&quot;\n&quot;);


return(0);
}
 
*****************************************************************
If you want to read and strore your file into a buffer,there are many ways to do it.
Here is an example:
Code:
#include<stdio.h>
#include<stdlib.h>
#define _MAXBUFF_   4096  // buffer size

void main()
{
    char Buffer[_MAXBUFF_] = {0};
    char c;
    int i = 0;

	FILE *fp;
    if(( fp = fopen( &quot;filename&quot;, &quot;r&quot; )) == NULL )
    {
        fputs(&quot; can't open the file \&quot;filename\&quot;&quot;, stderr);
        exit(0);
    }
    
    while(( c = getc( fp )) != EOF && i < _MAXBUFF_ )
    {
       Buffer[i] = c;
       i++;
    }
    
    fclose(fp);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top