Linux. C open创建文件,c-为什么open()用错误的权限创建我的文件?

我正在尝试从文件中读取一些文本,然后使用write()、read()和write()将其写入另一个文件。

这是我的write(),用于要写入的文件(我想创建一个新文件并将其写入):

fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

这将文件权限设置为我完全不了解的内容。 这是write()的输出:

---------T 1 chaitanya chaitanya 0 2010-02-11 09:38 test-1

甚至读取权限也被锁定。 我尝试搜索此内容,但找不到任何内容。奇怪的是,write()仍然成功地将数据写入文件。

另外,如果我执行“ chmod 777 test-1”,则事情将再次正常运行。

有人可以让我知道我的公开通话中哪里出问题了吗?

谢谢!

供您参考,我在下面粘贴了完整的程序:

#include

#include

#include

#include

int main () {

char buffer[512], ch;

int fIn, fOut, i;

ssize_t bytes;

FILE *fp = NULL;

//open a file

fIn = open ("test", O_RDONLY);

if (fIn == -1) {

printf("\nfailed to open file.");

return 1;

}

//read from file

bytes = read (fIn, buffer, sizeof(buffer));

//and close it

close (fIn);

printf("\nSuccessfully read %d bytes.\n", bytes);

//Create a new file

fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

printf("\nThese are the permissions for test-1\n");

fflush(stdout);

system("ls -l test-1");

//write to it and close it.

write (fOut, buffer, bytes);

close (fOut);

//write is somehow locking even the read permission to the file. Change it.

system("chmod 777 test-1");

fp = fopen ("test-1", "r");

if (fp == NULL) {

printf("\nCan't open test-1");

return 1;

}

while (1)

{

ch = fgetc(fp);

if (ch == EOF)

break;

printf("\n%c", ch);

}

fclose (fp);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在安卓内核中,可以使用file_open()函数来创建文件。以下是一个简单的示例代码: ```c #include <linux/fs.h> #include <linux/uaccess.h> static int __init my_init(void) { char *data = "Hello World!\n"; int len = strlen(data); struct file *filep; mm_segment_t old_fs; // 打开文件 filep = filp_open("/data/test.txt", O_CREAT | O_WRONLY, 0644); if (IS_ERR(filep)) { printk(KERN_ERR "Failed to create file\n"); return -1; } // 写入数据 old_fs = get_fs(); set_fs(KERNEL_DS); if (len != vfs_write(filep, data, len, &filep->f_pos)) { printk(KERN_ERR "Failed to write to file\n"); filp_close(filep, NULL); return -1; } set_fs(old_fs); // 关闭文件 filp_close(filep, NULL); return 0; } static void __exit my_exit(void) { vfs_unlink("/data/test.txt", NULL); } module_init(my_init); module_exit(my_exit); ``` 在上面的示例中,我们使用了filp_open()函数来创建文件并打开它。我们向该函数传递了文件路径、打开标志和文件权限。在这里,我们使用了O_CREAT标志,它将创建一个新文件(如果文件不存在),并使用指定的权限设置文件权限。打开标志还包括O_WRONLY,它表示我们将用于写入文件。 然后,我们使用vfs_write()函数向文件写入数据。该函数的参数是文件指针、写入的数据、数据长度和文件偏移量。我们还使用了set_fs()函数将地址空间从用户空间切换到内核空间,以便我们可以安全地访问用户空间的数据。 最后,在模块退出时,我们使用vfs_unlink()函数删除文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值