2011-06-11 78 views
0

我正在關注C編程教程http://www.cprogramming.com/tutorial/c/lesson10.html。這個特別的教程教導C中的文件I/O;特別是討論fopen命令。在一個點上,他們給下面的例子(我認爲應該打印文件test.txt的內容):初學者難以在C中使用fopen命令C

FILE *fp; 
fp=fopen("c:\\test.txt", "w"); 
fprintf(fp, "Testing...\n"); 

所以,我做了名爲test.txt的文本文件,並在我目前的救了它,工作目錄(C:\ cygwin \ home \ Andrew \ cprogramming)。然後,我創造了這個相同的目錄中交流文件,它包含以下代碼:

#include <stdio.h> 

int main() 
{ 
    FILE *fp; 
    fp=open("test.txt","w"); 
    fprintf(fp,"Testing...\n"); 
} 

當我編譯這個C文件使用gcc(我已經叫helloworld2.c),我得到以下信息:

helloworld2.c: In function `main': 
helloworld2.c:40: warning: assignment makes pointer from integer without a cast 

然後,當我嘗試運行可執行文件,我得到:你對我應該嘗試下什麼任何想法

Segmentation fault (core dumped) 

做什麼?

非常感謝您的時間。

+0

您的代碼段將「測試...」寫入文件,覆蓋文件中的所有內容。 – zneak 2011-06-11 20:11:05

+1

您是否知道在所有操作系統(包括Windows)上都可以使用正斜槓,而反斜槓只能在Windows上工作並且需要轉義?所以:-2代表反斜槓,+1代表正斜槓 - >在硬編碼路徑中使用正斜槓。 – ThiefMaster 2011-06-11 20:12:01

回答

6

這是因爲您使用open而不是fopenOpen是來自POSIX標準並返回一個(整數)句柄; fopen返回FILE結構的內存地址。你不能以可互換的方式使用兩者。就目前而言,您的代碼隱式地將收到的整數(可能是4)轉換爲FILE*指針,使其指向內存地址4.當fprintf試圖訪問它時,此段會錯誤地檢測您的程序。

fopen是跨平臺的,但是open是POSIX專用的。現在您可能想堅持使用fopen

+0

非常感謝! – Andrew 2011-06-11 20:22:08

3

fopen()返回一個指向一個FILE對象而open()返回文件描述符,其是一個純int
除非您需要低級別的功能,否則通常最好使用fopenFILE對象。

+0

非常感謝! – Andrew 2011-06-11 20:22:43

2

我猜這只是一個不幸的錯字 - open(),而不是fopen() - 這恰好工作不夠好,以建立一個最終的可執行文件(而不是使用open()蓄意)...

你請參閱warning: assignment makes pointer from integer without a cast,因爲open()<stdio.h>中沒有「原型」 - 參數聲明和返回類型。

如果沒有這樣的原型,編譯器會假定這樣一個函數存在並返回一個int,您的代碼將其分配給指針變量fp

,它實際是鏈接成功,因爲有一個函數在C庫調用open(),但它確實不同的東西(如其他人所說的)。但是,如果(例如)你寫入fpen(),事情就會變得更加明顯錯誤 - 在鏈接階段它會失敗,因爲沒有該名稱的庫函數。

如果編譯時啓用了更多警告 - 例如-Wall爲GCC - 你會得到一些更多有用的錯誤:

$ gcc -Wall -o helloworld2 helloworld2.c 
helloworld2.c: In function 'main': 
helloworld2.c:6: warning: implicit declaration of function 'open' 
helloworld2.c:6: warning: assignment makes pointer from integer without a cast 
helloworld2.c:8: warning: control reaches end of non-void function 
$ 

warning: implicit declaration of function 'open'告訴你,有你想使用的功能,你已經包括了頭之間的不匹配,和。