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
The only visible differences I can spot are from the this line:
You didn’t include the ‘.txt’ on the end of the file name in this instance.
The video has this line listed as:
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!
My terminal shows the different outut :
For me the program works. So maybe your compilation failed ?