我正在学习ShellWave的这个youtube教程,它教你如何在Linux设备上用C语言编程,由于某种原因,我被卡在第024课:youtube
我的代码如下(我使用与视频中相同的代码):
#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;
}
终端显示输出"创建并打开文件失败"。所以我认为我使用open()错误,或者它可能与我的Ubuntu版本有关?
有人能看出我做错了什么吗?我尝试更改标志的顺序,并尝试将模式更改为0777和0700,但没有成功。有一个权限被拒绝错误。由于某些原因,myfile.txt"是锁着的。chmod u=rwx,g=r,o=r myfile.txt命令对我有效。谢谢大家的快速帮助。
我能发现的唯一明显的差异来自这一行:
fd = open("myfile", O_WRONLY | O_CREAT, 0600);
在此实例中,您没有在文件名末尾包含' .txt '。
视频中有这样一行:
fd = open("myfile.txt”, O_CREAT | O_WRONLY, 0600);
o_create和O_WRONLY是错误的,尽管我不知道这是否会改变什么。
编辑:谢谢您的回复,已被告知订单无关紧要。
希望这对你有帮助!
我的终端显示了不同的输出:
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!
对我来说这个程序有效。所以也许你的编译失败了?