歡迎您光臨本站 註冊首頁

Linux下c語言fopen函數幾個小問題

←手機掃碼閱讀     火星人 @ 2014-03-26 , reply:0

1、使用fopen(文件打開)時,引號的區別。

char filename[20] = "NULL";
char directory[20] = "NULL";

printf ("please input the file name.\n");
scanf ("%s", filename);

fp = fopen ("filename", "w"); 加上引號將以filename本身為名在當前目錄下建立文件

fp = fopen (filename, "w"); 不加引號將以數組filename的值為名在當前目錄下建立文件

如果要在某個目錄下建立以數組filename的值為名的文件,可以如下這樣:
sprintf(directory,"/home/renewjoy/%s",filename); //sprintf可以連接兩個字元串

或者:strcpy(directory, "/home/renewjoy/"); //#include
strcat(directory, filename);

fp = fopen (directory, "w");

2、fopen中,貌似不能解析"~"符號,但可以解析"."、".."路徑。

fp = fopen ("~/study/c/test.c", "w"); 這樣會報錯。
fp = fopen ("$HOME/study/c/test.c", "w"); 同樣會報錯。
fp = fopen (/home/renewjoy/study/c/test.c, "w"); 必須用絕對路徑。
fp = fopen ("../test.c", "w"); 可以在當前目錄的父目錄下建立文件test.c

3、以寫的方式打開文件:fopen ("./open_file", "w"),並不能讀文件的內容,必須把打開方式設為讀和寫:"w+"

[火星人 ] Linux下c語言fopen函數幾個小問題已經有3248次圍觀

http://coctec.com/docs/linux/show-post-186587.html