-
help with fgetc
Is it possible to make fgetc skip to a new line once it encounters a certain character? Here is my code so far:
Code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
FILE *gfopen (char *fn, char *mode)
{
FILE *fp;
if ((fp = fopen (fn, mode)) == NULL){
fprintf (stderr, "Cannot open %s - bye\n", fn);
exit (1);
}
return fp;
}
int main (int argc, char **argv)
{
int c;
FILE *fp, *tmp_fp;
char array[50];
fp = gfopen (argv[1], "r+");
tmp_fp = tmpfile();
while ((c = getc(fp)) != EOF)
if ( c != ' '){
putc (c, tmp_fp);
}
rewind (tmp_fp);
while ((c = getc (tmp_fp)) != EOF)
printf("%c", c);
printf("\n");
return 0;
}
Whilst copying a text file into a temporary binary file I am removing all the spaces so if the text file contains:
Code:
Line 1: Example Example Example
Line 3: Example Example Example
it comes out like this:
Code:
Line1:ExampleExampleExample
Line3:ExampleExampleExample
which is what I want, but if I were to read from the binary file again, how can I make it read Line 1 and then skip straight to Line 3, if it sees that Line 2 is empty?
-
Binary files, by definition, are not text-files, and as such do not have lines. You can of course "define" a meaning to lines in a binary file - but your question is a bit strange in my opinion.
--
Mats
-
Ok then, suppose instead of a binary file I simply copy characters from one text file into another, whilst removing spaces between them (but blank lines still present).
My problem is that if the text file contains a complete blank line, then if I were to copy that line into an array(using fgetc), it would end up being filled with whitespaces, and writing a function that compares each array element to see if all of them contain whitespaces is, in my opinion a bit tedious. I tried various approaches but none were very successful. At the end of the day my goal is simple - to read in a text file whilst ignoring blank lines. I need some tips and advice on how to do that.
-
So, essentially what you want to do is that you skip a newline if that was the last thing written out? or read in, perhaps?
something like this:
Code:
...
char prev = 0;
...
while ((c = getc(fp)) != EOF)
if ( c != ' ' && (c != '\n' || prev != '\n'){
putc (c, tmp_fp);
prev = c;
}
...
This may not do EXACTLY what you wanted, but I think it will give you the general idea.
I would probably, actually, use fgets() to read a line at a time, strip out the spaces, and then see if the length of the string is 1 (only newline), and skip those single line strings on output. It may not be simpler, but if you want to deal with lines, then deal with lines.
--
Mats