Search code examples
cgcccompiler-errorsfopen

C function fopen(); error: too many arguments to the function


Why can I not do this?

fopen("%s",stringarray,fpointer);

The above returns an error that says too many arguments to function.

But this works,

fopen("file.txt",fpointer);

How can I get around this problem? Do I have to modify the headers in the code?


Solution

  • Assuming stringarray is a char * (really a chararray), simply pass it directly into fopen. There's no need to format it with %s, it's already a string.

    FILE *fp = fopen(stringarray, "r");
    

    Functions in C take very, very, very specific arguments. fopen takes a filename as a char * and the mode to open the file (read, write, etc...) as another char *. It returns a pointer to the opened file, or NULL if there was an error.


    If you did need to do some sort of formatting, you'd use sprintf to do the formatting and pass the result into fopen.

    // Allocate memory to store the result of sprintf
    char filename[256];
    char name[] = "foo";
    
    // filename = foo.txt
    sprintf(filename, "%s.txt", name);
    
    // Open foo.txt
    FILE *fp = fopen(filename, "r");