1 Replies - 944 Views - Last Post: 22 February 2009 - 02:12 AM Rate Topic: -----

#1 lwong26  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 12-February 09

Printing to a file within a function

Posted 22 February 2009 - 01:57 AM

I'm trying to print to a file from inside a function. Can't seem to figure it out. I think I have to use pointers?? But I am not sure how to use them. Heres the excerpt of the program



void Print(int arr[][5])
{
 

  fprintf(outfile,"B	 I	 N	 G	 O\n");
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[0][0],arr[0][1],arr[0][2],arr[0][3],arr[0][4]);
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[1][0],arr[1][1],arr[1][2],arr[1][3],arr[1][4]);
  fprintf(outfile,"%d	 %d   Free	%d	 %d\n",arr[2][0],arr[2][1],arr[2][3],arr[2][4]);
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[3][0],arr[3][1],arr[3][2],arr[3][3],arr[3][4]);
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[4][0],arr[4][1],arr[4][2],arr[4][3],arr[4][4]);
  fprintf(outfile,"\n\n\n\n\n");
}


int main()
{

  int i,j,num;
  int card[5][5]={0};
  FILE *outfile;
  outfile = fopen("bingo.txt","w");


  Print(card);
 


return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Printing to a file within a function

#2 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 291
  • View blog
  • Posts: 1,900
  • Joined: 25-October 06

Re: Printing to a file within a function

Posted 22 February 2009 - 02:12 AM

your function Print needs access to the FILE* outfile which is local to main(). You can either make it a global variable or pass it as a function parameter, e.g.
#include <stdio.h>
void Print(FILE *outfile, int arr[][5])
{


  fprintf(outfile,"B	 I	 N	 G	 O\n");
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[0][0],arr[0][1],arr[0][2],arr[0][3],arr[0][4]);
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[1][0],arr[1][1],arr[1][2],arr[1][3],arr[1][4]);
  fprintf(outfile,"%d	 %d   Free	%d	 %d\n",arr[2][0],arr[2][1],arr[2][3],arr[2][4]);
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[3][0],arr[3][1],arr[3][2],arr[3][3],arr[3][4]);
  fprintf(outfile,"%d	 %d	 %d	 %d	 %d\n",arr[4][0],arr[4][1],arr[4][2],arr[4][3],arr[4][4]);
  fprintf(outfile,"\n\n\n\n\n");
}


int main()
{

  int i,j,num;
  int card[5][5]={0};
  FILE *outfile;
  outfile = fopen("bingo.txt","w");


  Print(outfile, card);



return 0;
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1