Reputation: 67
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?
#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!
Upvotes: 2
Views: 410
Reputation: 565
Pre process stdin into a temp work file, this will then give you the control you require. Use function mkstemp.
Be warned stdin is a pipe, where as the fopen files are probably disk files
Upvotes: -1
Reputation: 3719
It isn't an issue with stdin
per se - if you want to wait to output your data, you will have to store it. You could write it to a file and read it back afterward. You could use malloc
and realloc
to store the data in memory. Mainly, if you don't want the data to output on every line, you need not to output it on every line.
Upvotes: 3