我正在关注C编程教程http://www.cprogramming.com/tutorial/c/lesson10.html.这个特殊的教程用C语言教文件I/O; 特别是,讨论了fopen命令.有一次,他们给出了以下示例(我认为应该打印文件test.txt的内容):
FILE *fp;
fp=fopen("c:\\test.txt", "w");
fprintf(fp, "Testing...\n");
Run Code Online (Sandbox Code Playgroud)
因此,我创建了一个名为test.txt的文本文件,并将其保存在我当前的工作目录中(C:\ cygwin\home\Andrew\cprogramming).然后我在同一目录中创建了ac文件,它包含以下代码:
#include <stdio.h>
int main()
{
FILE *fp;
fp=open("test.txt","w");
fprintf(fp,"Testing...\n");
}
Run Code Online (Sandbox Code Playgroud)
当我使用gcc编译这个c文件(我称之为helloworld2.c)时,我收到以下消息:
helloworld2.c: In function `main':
helloworld2.c:40: warning: assignment makes pointer from integer without a cast
Run Code Online (Sandbox Code Playgroud)
然后,当我尝试运行可执行文件时,我得到:
Segmentation fault (core dumped)
Run Code Online (Sandbox Code Playgroud)
你对我接下来应该尝试什么有什么想法吗?
非常感谢您的宝贵时间.
这是因为你使用open而不是fopen.Open来自POSIX标准并返回一个(整数)句柄; fopen返回FILE结构的内存地址.您不能以可互换的方式使用它们.就目前而言,您的代码隐式地将接收到的整数(可能是4)强制转换为FILE*指针,使其指向内存地址4.这会在fprintf尝试访问程序时对程序进行段错误处理.
fopen是跨平台的,但open仅限POSIX.你可能想要坚持到fopen现在.