用C语言调用fprintf语法中的函数

我正在尝试将我的字符串输出打印到一个单独的文件中。 我现在遇到的问题是我的代码带有一组字符串的函数,这些字符串在我的列下面添加了虚线(纯粹是化妆品)。 如何在我的fprintf代码中调用此函数?

#include  /* function for the dash-line separators*/ void dashes (void) { printf (" ---- ----- -------------------- --------------\n"); } /* end of function definition */ /* main program */ #include  #include  int main (void) { FILE *data_File; FILE *lake_File; FILE *beach_File; FILE *ecoli_Report; char fileName[10], lake_Table[15],beach_Table[15]; /*.txt file names */ char province[30] = ""; /*variable for the file Lake Table.txt*/ char beach[20]="",beach1[20]; /*variable for the file Beach Table.txt*/ char decision[15] = "CLOSE BEACH"; int lake_data=0,lake_x=0, beach_x=0, nr_tests=0; /* variables for the file july08.txt */ int province_data=0,prv_x=0; /* variables for the file Lake Table.txt */ int beach_data=0,bch_x=0; /* variables for the file Beach Table.txt*/ int j; double sum, avg_x, ecoli_lvl; printf ("Which month would you like a summary of? \nType month followed by date (ie: july05): "); gets(fileName); /*Opening the files needed for the program*/ data_File = fopen (fileName, "r"); lake_File = fopen ("Lake Table.txt", "r"); beach_File = fopen ("Beach Table.txt", "r"); ecoli_Report = fopen ("Lake's Ecoli Levels.txt", "w"); fprintf (ecoli_Report,"\n Lake Beach Average E-Coli Level Recommendation\n"); fprintf (ecoli_Report,"%c",dashes()); 

dashes()是无效的返回函数你将如何得到这一行?

  fprintf (ecoli_Report,"%c",dashes()); 

如果您需要在文件中打印该行,请制作原型并像这样调用,

  void dashes(FILE *fp){ fprintf(fp,"------------------\n"); } 

删除此行。

  fprintf (ecoli_Report,"%c",dashes()); 

并改变这样的呼唤,

  dashes(ecoli_Report); 

或者只是这样做,

  fprintf(ecoli_Report,"----------------"); 

如果您要按如下方式重新编写函数:

 char *strdashes (void) { return " ---- ----- -------------------- --------------"; } void dashes (void) { puts (strdashes()); } 

然后你可以用任何一种方式使用它。 调用dashes()仍会将字符串输出到标准输出后跟换行符,这相当于:

 printf ("%s\n", strdashes()); 

或者,您可以使用从strdashes()返回的字符串执行任意操作(a) strdashes()当然,除了尝试将其更改为字符串文字之外):

 fprintf (errorLog, "%s: %s\n", datetime(), strdashes()); 

(a)比如将它写入不同的文件句柄,用strlen()获取它的长度,用strcpy()它的副本,你可能想要用=替换所有-字符,真的有各种各样的可能性。

您需要更改破折号function以获取指向要用于输出的文件流的指针。 然后在函数中使用fprintf而不是printf。

或者,您可以使用破折号返回字符串( char * ),然后使用fprintf – 请注意您希望%s不是%c当前编码。

向函数添加FILE参数并将文件句柄传递给它,并在函数内使用fprintf。

或者,您可以使用破折号返回字符数组而不是void。