collinskewl2
collinskewl2

Reputation: 67

C, Passing a pointer of a file to a function

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char** argv)

{
    int good_file = 0;        //flag                    
    FILE* files[argc - 1];
    int i;
    for(i = 0; i < argc - 1; i++){

    if ((files[i]=fopen(argv[i+1], "r"))==NULL)
    {
        continue;
    }
    else                  //if file is good
    {
        good_file++;  //increment then pass the ptr
        test(files[i]);  //of file to test function
    }                         
}

    if(!good_file){              //if flag good_file is 0 error
        printf("ERROR!");
    }
exit(0);                           //then exit program

}

int test (int *file)                //takes in ptr to file[i] as param

{
    char c;
    while ((c = fgetc(file)) != EOF)
            putc(c, stdout);
        fclose(file);
    return main             //return main and continue loop

}

I know my code is a mess but I am trying to take in an X amount of files and then have the program test to make sure that the file isn't empty or doesn't exist and then print out the contents of it in a different function. I am trying to find a way to successfully pass a pointer to a file as a parameter so it's contents can then be printed to stdout in a different function. Then when done, have that function return control back to the main function for the loop to continue its process.

Upvotes: 0

Views: 138

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50775

Your test function is bogous (using int instead of FILE in the parameter and using char instead of int for fgetc.

Try this:

void test (FILE *file)                //takes in ptr to file[i] as param
{
    int c;
    while ((c = fgetc(file)) != EOF)
       putc(c, stdout);

    fclose(file);
}

There may be more issues though.

Upvotes: 1

Related Questions