skip to Main Content

I am studying this youtube tutorial by ShellWave which learns you how to program in C on a Linux device and for some reason am getting stuck at lesson #024 : Youtube

My code is the following (I used the same as in the video) :


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

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>


int main(int argc, char *argv[])
{
    int fd;
    char buf[14];
        
    //write
    
    fd = open("myfile.txt", O_WRONLY | O_CREAT, 0600);
    
    if(fd == -1)
    {
        printf("Failed to create and open the file. n");
        exit(1);
    
    }
    
    write(fd, "Hello World!n", 13);

    close(fd);
    
    //read
    
    fd = open("myfile.txt", O_RDONLY);
    
    if(fd == -1)
    {
        printf("Failed to open and read the file. n");
        exit(1);
    
    }
    
    read(fd, buf, 13);
    buf[13] = '';
    
    close(fd);
    
    printf("buf : %sn", buf);
    
    
    return 0;
}

The terminal shows output "Failed to create and open file". So I think I am using the open() wrong or maybe it has to do with my Ubuntu version?

Can somebody see what I am doing wrong?

I tried changing the order of the flags and tried to change the mode to 0777 and 0700 with no success.

There was a Permission Denied error. For some reason the "myfile.txt" was locked.
chmod u=rwx,g=r,o=r myfile.txt command worked for me. Thanks everyone for the quick help.

2

Answers


  1. The only visible differences I can spot are from the this line:

    fd = open("myfile", O_WRONLY | O_CREAT, 0600);
    

    You didn’t include the ‘.txt’ on the end of the file name in this instance.

    The video has this line listed as:

    fd = open("myfile.txt”, O_CREAT | O_WRONLY, 0600);
    

    The O_CREAT and O_WRONLY were the wrong way around, though I don’t know if this would change anything.

    Edit: Thank you kind replier, been informed the order does not matter.

    Hope this helps!

    Login or Signup to reply.
  2. My terminal shows the different outut :

    gcc t.c -Wall -Wextra
    t.c: In function ‘main’:
    t.c:11:14: warning: unused parameter ‘argc’ [-Wunused-parameter]
       11 | int main(int argc, char *argv[])
          |          ~~~~^~~~
    t.c:11:26: warning: unused parameter ‘argv’ [-Wunused-parameter]
       11 | int main(int argc, char *argv[])
          |                    ~~~~~~^~~~~~
    a@zalman:~/Dokumenty/t/t1$ ./a.out
    buf : Hello World!
    

    For me the program works. So maybe your compilation failed ?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search