mardi 28 avril 2015

C, how to stop stdin from outputting after each enter by the user?

I am new to C and I am encountering a problem with stdin I cannot find a solution to. My program either reads from file(s) or reads from stdin if no arguments (files) are provided by the user.

If the user doesn't supply any arguments then it will automatically read from stdin. My program is supposed to take in input (from file or stdin) and then remove the blank lines from it.

My problem arises when the program reads from stdin. Every time the user types something then presses enter the program automatically out puts the results. When i'd prefer enter to just be a newline. How can I make it so the program waits for the user to hit EOF instead of each enter?

Here is my code:

#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; i < 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 (! is_all_white(buffer)) {
            fputs(buffer, stdout);
    }
}


int is_all_white(char *s) {
    while (*s) {
        if (!('\n' == *s || '\t' == *s || ' ' == *s)) return 0;
        s += 1;
    }
    return 1;
}

I appreciate any feedback!

Aucun commentaire:

Enregistrer un commentaire