Metin Oktay Yılmaz Metin Oktay Yılmaz - 1 year ago 72
C Question

A simple text file wouldn't be created [C, GCC]

Update: The problem with this question is the failure of realizing that ´opening´ a file and ´creating´ a file are different things. When English is the second language, such errors inevitably occur. I'm sorry.

Note: I would like to apologise from @Weather Vane for my mean words. His comment on the answer of @Nunchy is his second comment in this thread. I saw his second comment (in which I'm being scolded) before his first comment (in which the answer to my question is), and I was like "WTF?". So yeah, this explains yesterday's conflict.

Thanks for reading.

End of Update and Note

Below is a simple code that should open

, and then close it. It compiles without error, nor warning, but file wouldn't be created. However, a segmentation fault is thrown when code is executed.

Thanks for your kind help in advance.

#include "stdio.h"

void main() {
FILE *fp;
fp = fopen("SIZE.txt", "r+");

Answer Source

The primary reason for the failure was due to the specification of the file mode as "r+" which will only open existing files, not create new files. A file is only created if "w+", "a", or "a+" is specified as the file mode.

check this, if file exists it will be display file already exist, but if the file doesn't exist it will be create it, depend what are you going to do, the ab+ you can just change to w

FILE *fp;
fp = fopen("SIZE.txt", "r");
    fp=fopen("SIZE.txt", "ab+");
    printf("File was created\n");
    printf("File already exists\n");
return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download