您好,我在 C 中練習檔案處理,并嘗試撰寫有關洗掉注釋的代碼。我用 main.c、functions.c 和 functions.h 制作它。
主檔案
#include <stdio.h>
#include <stdlib.h>
#include "functions.c"
int main(void) {
FILE *in ,*out;
char c;
if ((in = fopen("input_file.c", "r")) == NULL ) {
printf("Error opening \"file1.txt\" for reading\n");
exit(1);
}
if ((out = fopen("input_file.nocmments.c","w")) == NULL ) {
printf("Error opening \"file2.txt\" for writing\n");
exit(2);
}
while((c = getc(in)) != EOF) {
if(c == '/') comment(c, in, out);
else if (c == '\'' || c == '\"') quotes(c, in, out);
else print(c, out);
}
fclose(in);
fclose(out);
return 0;
}
function.c(我只展示一部分,因為其他函式也有同樣的問題
int one_line(char ch, FILE* fpin, FILE* fpout) {
while ((ch = getc(fpin)) != '\n');
fputc(ch, fpout);
return ch, fpin, fpout; <-- error here
}
函式.h
int comment(char ch, FILE* fpin, FILE* fpout);
int one_line(char ch, FILE* fpin, FILE* fpout);
int multiline(char ch, FILE* fpin, FILE* fpout);
int quotes(char ch, FILE* fpin, FILE* fpout);
int print(char ch, FILE* fpout);
所以當我編譯代碼時,我收到以下警告
returning ‘FILE *’ {aka ‘struct _IO_FILE *’} from a function with return type ‘int’ makes integer from pointer without a cast [-Wint-conversion]
我知道我無法回傳typedef,這就是為什么我遇到以下問題,但是如何將檔案指標回傳到我的主函式?(對不起,如果我的問題很愚蠢)
uj5u.com熱心網友回復:
int one_line(char ch, FILE* fpin, FILE* fpout) {
while ((ch = getc(fpin)) != '\n');
fputc(ch, fpout);
return ch, fpin, fpout; <-- error here
}
C 有一些棘手或令人困惑的細節。逗號運算子就是其中之一。
return ch, fpin, fpout;
這是有效的 C 代碼。逗號運算子在 C11 第 6.5.17 節中定義,它說:
逗號運算子的左運算元被計算為空運算式;在它的評估和右運算元的評估之間有一個序列點。然后評估正確的運算元;結果有其型別和值。
在您的示例中,這意味著:
- 首先,對運算式
ch求值,由于它沒有任何副作用,因此被忽略。 - 其次,也
fpin被評估和忽略。 - 第三,
fpout被評估并從函式回傳。
該型別的fpout就是FILE *,函式的回傳型別int,這些型別不匹配,這是在編譯器警告從何而來。
您應該將代碼更改為簡單的return ch.
您不需要從函式中回傳檔案,即使您修改了它們。這里的重點是您沒有將實際檔案傳遞給函式,而是將指向檔案的指標。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366252.html
上一篇:如何在C中讀取大資料?[復制]
