I'm using Ubuntu 18.04 on VMWare Fusion. I have no idea why the file doesn't open using fopen() function in C. The code is below.

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(void) {
          char *fname = "file.txt";
          FILE *fp;

          if((fp = fopen(fname, "w")) != NULL) {
                 fprintf(stderr, "open error for %s, errno = %d\n", fname, errno);
         return 0;

And the result is below.

$ ./a.out 
open error for file.txt, errno = 0

My Ubuntu memory is like that.

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            1.9G     0  1.9G   0% /dev
tmpfs           393M  2.1M  391M   1% /run
/dev/sda1        19G   14G  3.9G  79% /
tmpfs           2.0G     0  2.0G   0% /dev/shm
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           2.0G     0  2.0G   0% /sys/fs/cgroup
tmpfs           393M   16K  393M   1% /run/user/122
tmpfs           393M   36K  393M   1% /run/user/1000

1 Answer 1


this statement

if((fp = fopen(fname, "w")) != NULL) { 

should be:

if((fp = fopen(fname, "w")) == NULL) {

I.E. the posted code is checking for the success condition and calling it an error

on a related note:

this statement:


is NOT how to close a file

rather use:

fclose( fp );



tells disk space usage

To display the information about files use:

ls -al

Strongly suggest making extensive use of the man pages for any functions you want to use.

Not the answer you're looking for? Browse other questions tagged or ask your own question.