arrays - C program that reads from file or stdin and removes blank lines -
i new c , here have c program take in x amount of files command line , output files stdout deletes blank lines. if user doesn't input files read directly stdin.
everything functions smoothly except removing of lines.
here program
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define numchars 1024 int main (int argc, char** argv) { int good_file = 0; if(argc <= 1){ good_file++; test(stdin); } file* files[argc - 1]; int i; for(i = 0; < argc - 1; i++){ if ((files[i]=fopen(argv[i+1], "r"))==null){ continue; } else{ good_file++; test(files[i]); } } if(!good_file){ fprintf(stderr, "error!\n"); } } int test (file *file) { char buffer[numchars]; while (fgets(buffer, numchars, file) != null) part2(buffer); fclose(file); } int part2 (char *buffer) { if(*buffer != '\n' || *buffer != '\t' || *buffer != ' '){ //if(*buffer != '\n') deletes (skips) plain newlines fputs(buffer, stdout); } } in function part 2, can see comment program delete (skips) just newlines if remove || '\t' , ' ' in if statement. lot of blank lines not "blank". i.e have tabs or white space on them. using logic had removing newlines applied tabs , white space well.
but new implementation won't skip newlines. , doesn't work ever.
appreciate feedback!
your condition here true, precisely nothing:
if (*buffer != '\n' || *buffer != '\t' || *buffer != ' ') { fputs(buffer, stdout); } you're asking "is first character not newline or not tab or not space?" every character can that: space not newline, , newline not tab. need check characters in line:
int is_all_white(char *s) { while (*s) { if (!('\n' == *s || '\t' == *s || ' ' == *s)) return 0; s += 1; } return 1; } ... if (! is_all_white(buffer)) { fputs(buffer, stdout); }
Comments
Post a Comment