[英]Calling a function within fprintf syntax in C language
我正在嘗試將字符串輸出打印到單獨的文件中。 我現在遇到的問題是我的代碼帶有一組字符串的函數,該函數在我的列(純粹是修飾符)下添加了虛線。 如何在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());
dashes()
是void返回函數,您將如何獲得此行?
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());
(一)如將其寫入到不同的文件句柄,得到它與長度strlen()
使得它與復制strcpy()
你可能要全部更換-
字符=
,真是各種各樣的可能性。
您需要更改破折號功能以獲取指向要用於輸出的文件流的指針。 然后在函數中使用fprintf而不是printf。
另外,您也可以使用破折號返回字符串( char *
),然后使用fprintf-注意,您希望%s
而不是當前編碼的%c
。
將FILE參數添加到函數中,並將文件句柄傳遞給它,然后在函數內部使用fprintf。
或者,您可以讓破折號返回一個字符數組而不是void。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.