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.
This is because you use
openinstead offopen.Openis from the POSIX standard and returns an (integer) handle;fopenreturns the memory address of aFILEstructure. You cannot use both in an interchangeable way. As it stands, your code implicitly casts the received integer (likely 4) to aFILE*pointer, making it point to the memory address 4. This segfaults your program whenfprintfattempts to access it.fopenis cross-platform, butopenis POSIX-only. You may want to stick tofopenfor now.