在C中使用fopen命令的初学者很难(Difficulty for a beginner using fopen command in C)

编程入门 行业动态 更新时间:2024-10-28 20:21:10
在C中使用fopen命令的初学者很难(Difficulty for a beginner using fopen command in C)

我正在关注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");

所以,我创建了一个名为test.txt的文本文件,并将其保存在我当前的工作目录中(C:\ cygwin \ home \ Andrew \ cprogramming)。 然后我在同一目录中创建了ac文件,它包含以下代码:

#include <stdio.h> int main() { FILE *fp; fp=open("test.txt","w"); fprintf(fp,"Testing...\n"); }

当我使用gcc编译这个c文件(我称之为helloworld2.c)时,我收到以下消息:

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

然后,当我尝试运行可执行文件时,我得到:

Segmentation fault (core dumped)

你对我接下来应该尝试什么有什么想法吗?

非常感谢您的宝贵时间。

I am following the C programming tutorial at http://www.cprogramming.com/tutorial/c/lesson10.html. This particular tutorial teaches file I/O in C; in particular, the fopen command is discussed. At one point, they give the following example (which I think should print the contents of file test.txt):

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

So, I made a text file called test.txt and saved it in my current, working directory (C:\cygwin\home\Andrew\cprogramming). Then I created a c file in this same directory, and it contains the following code:

#include <stdio.h> int main() { FILE *fp; fp=open("test.txt","w"); fprintf(fp,"Testing...\n"); }

When I compile this c file (which I've called helloworld2.c) using gcc, I get the following messages:

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

Then when I try to run the executable, I get:

Segmentation fault (core dumped)

Do you have any ideas about what I should try next?

Thank you very much for your time.

最满意答案

这是因为你使用open而不是fopen 。 Open来自POSIX标准并返回一个(整数)句柄; fopen返回FILE结构的内存地址。 您不能以可互换的方式使用它们。 就目前而言,您的代码隐式地将接收到的整数(可能是4)转换为FILE*指针,使其指向内存地址4.当fprintf尝试访问它时,会对程序进行段错误处理。

fopen是跨平台的,但open是仅POSIX。 你现在可能想坚持下去。

This is because you use open instead of fopen. Open is from the POSIX standard and returns an (integer) handle; fopen returns the memory address of a FILE structure. You cannot use both in an interchangeable way. As it stands, your code implicitly casts the received integer (likely 4) to a FILE* pointer, making it point to the memory address 4. This segfaults your program when fprintf attempts to access it.

fopen is cross-platform, but open is POSIX-only. You may want to stick to fopen for now.

更多推荐

本文发布于:2023-07-31 08:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1342584.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:很难   初学者   命令   fopen   beginner

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!