So I created a function is able to pull the header from a file and put it into a new file without the comments. All the .ppm files have a max color value of 255 so here is my function:
void headerinfo(FILE *infile, FILE *outfile){
char line[100];
int c;
fgets(line,100,infile);
c=strlen(line);
while(line[c]!='\n' && line[c-1]!='5' && line[c-2]!='5' && line[c-3]!='2'){
if(line[0]=='#'){
fgets(line,100,infile);
c=strlen(line);
}
else{
fputs(line,outfile);
fgets(line,100,infile);
c=strlen(line);
}
}
fputs(line,outfile);
}
The issue I am running into is that I have two .ppm files with similar header formats, but the one with 561 by 375 dimensions does not output the last line with 255 onto the new file. Is there a difference between these two files that is affected by my code?
Here is the .ppm file that does not copy over the 255 line
The while
conditions are wrong. Since c
is the length of the string, line[c]
points to the null character that ends it. It can never be '\\n'
. And line[c-1]
is the '\\n'
that ends a line (except possibly for the last line in a file), so it is never '5'
(unless the last line ends with '5'
). And of course line[c-2]
and line[c-3]
are also out of position.
What you actually want is:
while (! (4 <= c && line[c-4] == '2' && line[c-3] == '5' && line[c-2] == '5' && line[c-1] == '\n')) {
With some improvements:
void headerinfo(FILE *infile, FILE *outfile)
{
char line[100];
size_t c;
do
{
fgets(line, sizeof line, infile);
c = strlen(line);
if (line[0] != '#')
fputs(line, outfile);
} while (! (4 <= c && strcmp(&line[c-4], "255\n") == 0));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.