According to http://en.wikipedia.org/wiki/Netpbm_format the file starts with a two byte sequence: P1
, P2
, P3
(as Human readable Text - ASCII). So reading this into an int
will not work. You should read in a char
(for the P
) and then another char
for the number and to find out what format your file is. Then depending on the format take further steps.
Basic file I/O of a ppm file
Question
I'm trying to write a program to read through a .ppm file and keep the data in a struct. To be able to do that though, I need to be able to open the file, which is not working so far. I'm obviously doing something wrong. Can you please take a look at the code and see if you can find out what's the problem?
#include <stdio.h>
#include <stdlib.h>
int readFile(char *filename);
int main(void)
{
readFile("myfile.ppm");
return 0;
}
int readFile(char *filename)
{
int x = 0;
FILE *pFile;
pFile = fopen(filename, "rb");
if(!pFile)
{
fprintf(stderr, "Unable to open file %s\n", filename);
exit(1);
}
fscanf(pFile, "%d", &x);
fclose(pFile);
printf("%d\n", x);
return 0;
}
This just gives me an "\n" on the stdout. Should I fscanf it into an array rather than an int?
Based on your feedback I edited the code to scanning to two chars:
int readFile(char *filename)
{
char first, second = 0;
FILE *pFile;
pFile = fopen(filename, "rb");
if(!pFile)
{
fprintf(stderr, "Unable to open file %s\n", filename);
exit(1);
}
fscanf(pFile, "%c%c", &first, &second);
fclose(pFile);
printf("First: %c, Second: %c\n", first, second);
return 0;
}
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow