1

I am attempting to write an array of the first N primes to a txt file in rows of 5 entries each, with 10 spaces between each entry. The relevant code is as follows:

#include<stdio.h>
#include<math.h>

#define N 1000

...

void writePrimesToFile(int p[N], char filename[80])
{
    int i;
    FILE *fp = fopen(filename, "w");
    for(i = 0; i<=N-1; i++)
    {
        for(i = 0; i<5; i++)
        {
            fprintf(filename, "%10%i", p[i]);
        }
        printf("/n");
    fclose(fp);
    }


    printf("Writing array of primes to file.\n");
}

The compiler throws the following error:

primes.c:40:4: warning: passing argument 1 of ‘fprintf’ from incompatible pointer type [enabled by default]
    fprintf(filename, "%10%i", p[i]);
    ^
In file included from /usr/include/stdio.h:29:0,
                 from primes.c:1:
/usr/include/stdio.h:169:5: note: expected ‘struct FILE *’ but argument is of type ‘char *’
 int _EXFUN(fprintf, (FILE *, const char *, ...)
     ^

Numerous Google searches have not been fruitful. Any help would be much appreciated.

1
  • 2
    The error message could not be more clear: expected ‘struct FILE *’ but argument is of type ‘char *’ Commented Oct 27, 2013 at 23:57

4 Answers 4

4

Test the output of fopen() before allowing fp to be used:

FILE *fp = fopen(filename, "w");   
if(fp)//will be null if failed to open
{
    //continue with stuff
    //...    
}

Also 1st argument to fprintf(...) is of type FILE *. Change:

fprintf(filename, "%10%i", p[i]);
        ^^^^^^^^

to

fprintf(fp, "%i", p[i]);
        ^^//pointer to FILE struct
Sign up to request clarification or add additional context in comments.

Comments

1

You must use the FILE * that you obtained when you opened the file.

   fprintf(fp, "%10%i", p[i]);

The error message states that fprintf function expects a FILE *, not a char * (or, what is the same, a char[]).

Comments

0

Right. All the C compiler sees, when you call fprintf, is a string literal (a char*) and it is not designed to infer that a string refers to a filename. That's what fopen is for; it gives you a special type of pointer that indicates an open file. Note that your code doesn't actually do anything with fp after it opens the file, except to close it. So you just need to substitute fp in for filename in your call to fprintf.

Comments

0
  1. Should check the return value of fopen.

  2. Should be:

    fprintf(fp, "%10d", p[i]);

  3. Should move fclose out of the outer for loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.