Cesar A
Cesar A

Reputation: 693

Reading chars from multiple files in C

I am trying to read all the chars that are in different files. For example, by calling myprogram < file1 file2.

My approach is the following:

void do_read(FILE * file){
char ch;

    while (ch != EOF) {
        ch = getc(file);


        printf("%c\n", ch);
}

int main(int argc, char * argv[])
{
    int i = 1;
    FILE * fp = NULL;

    if (argc < 1) {
        //Error. No file given
printf("Error");
    }
    else {
        // cycle through all files in command line arguments and read them
        for (i=1; i < argc; i++) {
            if ((fp = fopen(argv[i], "r")) == NULL) {
                printf("Failed to open file.\n");
            }
            else {
                do_read(fp);
                fclose(fp);
            }
        }
    }

    return 0;
}

But whenever I try to run it even as myprogram < file1 (with only 1 argument) it doesn't output anything. Not even the printf("Error").

Can anyone help me to fix my code please? What am I doing wrong? Is there a better approach?

Thank you so much for your help in advance!

Upvotes: 2

Views: 47

Answers (1)

Aioi Yuuko
Aioi Yuuko

Reputation: 118

myprogram < file1 is essentially shorthand for cat file1 | myprogram, that is, your program would want to read stdin to get the contents of that file. The invocation you want is myprogram file1 file2.

Also, your do_read function is broken, because it'll even print the char when it is EOF. Instead of checking before you get, check when you get:

void do_read(FILE * file){
    char ch = '\0';

    while (ch != EOF) {
        ch = getc(file);
        printf("%c\n", ch);
    }
}
/* Becomes: */
void do_read(FILE * file){
    char ch = '\0';

    while ((ch = getc(file)) != EOF) {
        printf("%c\n", ch);
    }
}

Upvotes: 2

Related Questions