2013-04-01 28 views
4

我在學習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 

有什麼想法?謝謝你的時間。

+1

我想你在調用系統調用['write()'](http://linux.die.net/man/2/write)。也許在main()之上包含一個原型,並且更好的是,選擇一個在系統調用時未使用的名稱。 – WhozCraig

+1

你的函數沒有錯,問題是選擇的名字(在unistd.h中使用「寫」)http://pubs.opengroup.org/onlinepubs/009695399/functions/write.html –

+1

謝謝大家,對不起,這是一個漫長的夜晚。 –

回答

7

你缺乏你的函數的函數原型。此外,writeunistd.h中聲明,所以這就是爲什麼你會得到第一個錯誤。嘗試將其重命名爲my_write或其他東西。除非您計劃在以後使用其他功能,否則您實際上只需要使用stdio.h庫。我添加錯誤檢查fopen以及return 0;應斷定各主要功能C.

這裏是我會做什麼:

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 

void my_write(FILE *fp, char *str) 
{ 
    fprintf(fp, "%s", str); 
} 

int main(void) 
{ 
    char *str = "test text\n"; 
    FILE *fp; 

    fp = fopen("test.txt", "a"); 
    if (fp == NULL) 
    { 
     printf("Couldn't open file\n"); 
     return 1; 
    } 
    my_write(fp, str); 

    fclose(fp); 

    return 0; 
} 
0

請參閱linux的man 2 write

#include <unistd.h> 

    ssize_t write(int fd, const void *buf, size_t count); 

這是原型。您需要傳遞整數文件描述符而不是文件指針。 如果你想要你自己的功能更改名稱foo_write或東西

0

有已經叫write的系統功能。只要將你的函數命名爲別的東西,在你使用它之前先放一個函數聲明,你就會好的。

+1

「你會好起來的」 - 錯了。該功能必須在使用前聲明。 –

相關問題