tags:

views:

100

answers:

4

If I had an array of integers I wanted to output to a text file..

void output()
{   
    for (i=0; i<10; i++)
        printf("%d ", values[i]);
}

How can I save the output() to text file using the method below?

void writeToFile()
{   
    file = fopen("file.txt","a+"); // apend file or create a file if it does not exist
    fprintf(file,"%d", *missing parameter*); // write
    fclose(file); // close file
    printf("File created. Located in the project folder.\n", "");
}
A: 

Just create two functions:

void output()
{   
    for (i=0; i<10; i++)
        printf("%d ", values[i]);
}

void output(FILE* file)
{   
    for (i=0; i<10; i++)
        fprintf(file, "%d ", values[i]);
}
AareP
+1 for the blank after %d
stacker
C does not support overloading ;-)
Denis Krjuchkov
-1 . C doesn't support overloading. The second function is enough: "void output(FILE *file);"If you want to print to stdout, you can use the second function like this: output(stdout);
Andrei Ciobanu
+4  A: 

As an alternative to creating two functions (as per AareP's answer), you could add a destination parameter to the output() function:

void foutput(FILE *dest, int values[])
{   
    int i;

    for (i=0; i<10; i++)
        fprintf(dest, "%d ", values[i]);
}

You can then reimplement the original output() as a simple wrapper:

void output(int values[])
{
    foutput(stdout, values);
}

This might not seem too useful in this case, but I've put it here because this general pattern can be useful when the logic of the output function is more complicated. In general it's better to keep it in one place than to replicate it across multiple functions (it means you only have to fix bugs in one place, for one thing).

caf
+1  A: 

Adding to what others have told:

You must always check for errors after fopen, which on error return NULL.

FILE *file = fopen("file.txt","a+"); 
if(!file) {
        fprintf(stderr,"error opening file...exiting\n");
        exit(1);
}
codaddict
A: 

If you want to reuse your output function you can do something like this. Using the a_output function you will be able to print the results both in console, or any other output stream.

#include <assert.h>
#include <stdio.h>

void a_output(FILE *fs, int *array, unsigned int array_s);

void a_output(FILE *fs, int *array, unsigned int array_s){
    int i;

    assert(fs != NULL);
    assert(array != NULL);

    for(i = 0; i < array_s ; i++){
        fprintf(fs, "%d ", array[i]);
    }
}

int main(int argc, char **argv)
{
    int array[5] = {1, 2, 3, 4, 5 };
    FILE *out;

    if((out = fopen("output.txt", "w")) == NULL){
        return -1;
    }
    /* Will "print" results in a file */
    a_output(out, array, 5);

    /* Will "print" results in console */
    a_output(stdout, array, 5);

    fclose(out);
    return 0;
}
Andrei Ciobanu