最近在学习linuxC文件读写函数,将文件权限创建为644,代码如下:
IO_file.c
#include "IO_file.h"
char write_buff[20] = {0};
char read_buf[20] = {0};
#define FILE_CHMOD S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH
void Config_file_init(void)
{
int file_fd = 0;
ssize_t write_ret = 0;
size_t write_count = 0;
off_t lseek_ret = 0;
ssize_t read_ret = 0;
file_fd = open("./config_file.txt",O_RDWR|O_CREAT,FILE_CHMOD);
if(file_fd == -1)
{
printf("file open failed\r\n");
return;
}
else
{
printf("file open success %#o\r\n",FILE_CHMOD); //%#o:八进制输出 此处打印644
}
sprintf(write_buff,"hello_world\r\n");
write_count = strlen(write_buff);
write_ret = write(file_fd, write_buff, write_count);
if(write_ret == write_count)
{
printf("file write success\r\n");
}
else
{
printf("file write err\r\n");
}
lseek_ret = lseek(file_fd, 0, SEEK_SET);
if(lseek_ret == -1)
{
printf("file lseek err \r\n");
close(file_fd);
}
else
{
printf("file lseek success\r\n");
}
read_ret = read(file_fd, read_buf, sizeof(read_buf));
if(read_ret != -1)
{
printf("file read success:%s\r\n",read_buf);
}
close(file_fd);
}
IO_file.h
#ifndef __IO_FILE_H
#define __IO_FILE_H
#include "main.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void Config_file_init(void);
#endif
main.c
int main(void)
{
Config_file_init();
return 0;
}
linux环境下编译运行此程序
vmuser@ubuntu:/mnt/hgfs/share/Study_Proj$ gcc main.c IO_file.c -o num01.out
vmuser@ubuntu:/mnt/hgfs/share/Study_Proj$ ./num01.out
file open success 0644
file write success
file lseek success
file read success:hello_world
vmuser@ubuntu:/mnt/hgfs/share/Study_Proj$ ls -l config_file.txt
-rwxrwxrwx 1 root root 0 Jun 7 01:59 config_file.txt
此时config_file.txt 创建成功,但是权限不对,查百度在open()函数前面加 umask(0133); 或 umask(0000); 最后运行也不对,因为即使在程序中修改umask的值,父进程的值仍然不会变,在linux虚拟机上查看umask始终是0022
vmuser@ubuntu:/mnt/hgfs/share/Study_Proj$ umask
0022
然后想着试一下用chmod看看能不能修改,结果即使用chmod也无法修改权限,仍然是-rwxrwxrwx
最后查资料https://blog.csdn.net/apple_51931783/article/details/121129020
发现是因为我的文件夹是在共享文件夹下的问题
接下来尝试将config_file.txt 复制在Home目录下,通过chmod修改成功,删除文件,重新运行程序,查看权限正确。
vmuser@ubuntu:~/C_Proj$ gcc main.c IO_file.c -o num01.out
vmuser@ubuntu:~/C_Proj$ ./num01.out
file open success 0644
file write success
file lseek success
file read success:hello_world
vmuser@ubuntu:~/C_Proj$ ls -l config_file.txt
-rw-r--r-- 1 vmuser vmuser 13 Jun 7 02:30 config_file.txt
至于为什么在共享文件夹下权限无法修改,后面还得继续研究