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

时间:2015-02-20 06:28:59

标签: c function text-files

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

#include <stdio.h>
/* function for the dash-line separators*/
void
dashes (void)
{
printf ("  ----           -----        --------------------     --------------\n");
}
/* end of function definition */

/* main program */
#include <stdio.h>
#include <string.h>
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 (i.e: 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());

4 个答案:

答案 0 :(得分:5)

dashes()无效返回功能你将如何获得这一行?

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

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

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

删除此行。

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

并改变这样的呼召,

 dashes(ecoli_Report);

或者只是这样做,

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

答案 1 :(得分:3)

如果你按照以下方式重新编码你的功能:

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

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

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

或者,您可以使用从strdashes()返回的字符串执行任意操作(a)(除了尝试更改)它当然是一个字符串文字):

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

(a)例如将其写入不同的文件句柄,使用strlen()获取其长度,并使用{{复制它1}}您可能希望用strcpy()替换所有-个字符,实际上有各种各样的可能性。

答案 2 :(得分:2)

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

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

答案 3 :(得分:2)

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

或者,您可以使用短划线返回字符数组而不是void。