日期:2014-05-16  浏览次数:20623 次

linux下fopen函数的使用
请问在linux系统下使用fopen函数,文件名如何设置,比如根目录下mnt目录下的std.txt文件(std.txt最初不存在),是不是应该写成fopen("/mnt/std.txt","wb")。我这样写运行后返回值是NULL,表明打开失败。请问该如何写路径?

------解决方案--------------------

我觉得是权限相关。

换root运行一下程序。

需要对目录有可写权。
------解决方案--------------------
2 楼说得没错.
因为 mnt 一般是 drwxr-xr-x root root 的权限, 你没有创建文件的权限.

------解决方案--------------------
支持前面两楼
------解决方案--------------------
是这样的再输入文件路径的时候要注意: 
你的方向错了应该是"\"这样的反斜杠而且要输入两个反斜杠 
因为字符串中的1个反斜杠的意思就是说他是个转意字符只有\\的时候才会显示出来1个字符向你的那个路径就应该写成fp=fopen("\\mnt\\yaffs\\red.txt")
----
以上内容来自百度知道
http://zhidao.baidu.com/question/25081701.html?si=1
------解决方案--------------------
楼上说的那个, \\ 是windows下的路径分隔符号.

我还是给出具体实例吧:

[henryfour@www test]$ cat a.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

int main() {
FILE* file_desc;

file_desc = fopen("/mnt/std.txt", "wb");
if (file_desc == NULL)
printf("error\n");
return 0;
}


[henryfour@www test]$ ll /mnt/std.txt
-rw-r--r-- 1 root root 0 01-09 20:06 /mnt/std.txt
[henryfour@www test]$ ./a.out
error
[henryfour@www test]$ su -c "chmod o+w /mnt/std.txt"
口令:
[henryfour@www test]$ ./a.out

------解决方案--------------------
fopen后边加一句
perror(NULL);
看看是什么原因