我在學習C,我來自Java背景。如果我能得到一些指導,我將不勝感激。這裏是我的代碼:如何使用FILE作爲C中函數的參數?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
char *str = "test text\n";
FILE *fp;
fp = fopen("test.txt", "a");
write(fp, str);
}
void write(FILE *fp, char *str)
{
fprintf(fp, "%s", str);
}
當我嘗試編譯,我得到這個錯誤:
xxxx.c: In function ‘main’:
xxxx.c:18: warning: passing argument 1 of ‘write’ makes integer from pointer without a cast
/usr/include/unistd.h:363: note: expected ‘int’ but argument is of type ‘struct FILE *’
xxxx.c:18: error: too few arguments to function ‘write’
xxxx.c: At top level:
xxxx.c:21: error: conflicting types for ‘write’
/usr/include/unistd.h:363: note: previous declaration of ‘write’ was here
有什麼想法?謝謝你的時間。
我想你在調用系統調用['write()'](http://linux.die.net/man/2/write)。也許在main()之上包含一個原型,並且更好的是,選擇一個在系統調用時未使用的名稱。 – WhozCraig
你的函數沒有錯,問題是選擇的名字(在unistd.h中使用「寫」)http://pubs.opengroup.org/onlinepubs/009695399/functions/write.html –
謝謝大家,對不起,這是一個漫長的夜晚。 –