anthony
anthony

Reputation: 401

print characters from an array to an output file in C

I want to write a method called print array that has 2 parameters seen below.

I want to, most likely using a for loop, iterate through the array of characters and pass each character to the output text file to be printed on that file on the same line. so if the array has a, b, c, d, e, f, g. in the file I want it to display abcdefg. I dont really know how to get it started.

void printArray(char * array, FILE * fout)
{
    //i think using a for loop is the way to go, i just dont know exactly what to do after
}

Upvotes: 0

Views: 12505

Answers (2)

Chani
Chani

Reputation: 5165

Try this:

void printArray(char * array, FILE * fout, int MAX_CHAR)
{ 
     int i;
     fout = fopen("file.txt","a+");      /* open the file in append mode */
     for (i=0; i<MAX_CHAR; i++)
          fprintf(file,"%c",*(array+i)); /* write */ 
     fclose(file);                       /* close the file pointer */ 

     return 0; 
}

Upvotes: 2

tbert
tbert

Reputation: 2097

It's called fputs(). POSIX standard, because this problem has been solved before by multiple people who also needed to print character arrays (or to "put a string") into a FILE.

You can either just use the code as-is from your friendly local standard C library, or you can read it to figure out what you need to do to do so yourself, should you feel the need.

EDIT: try the following to get you started https://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=7425&lngWId=3

Upvotes: 2

Related Questions