我正在尝试从一个文件中读取一些文本,然后使用 open()
、read()
和 write()
将其写入另一个文件>.
这是我要写入的文件的 open()
(我想创建一个新文件并写入其中):
fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);
这是将文件权限设置为我完全不理解的东西。这是 ls -l
的输出:
---------T 1 chaitanya chaitanya 0 2010-02-11 09:38 test-1
连读取权限都被锁定了。我试着搜索这个,但找不到任何东西。
奇怪的是,write()
仍然成功地将数据写入文件。
此外,如果我执行“chmod 777 test-1”,一切又会开始正常工作。
有人可以让我知道我在公开电话 session 中哪里出了问题吗?
谢谢!
为了您的引用,我把完整的程序贴在下面:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
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;
}
最佳答案
open() 接受第三个参数,即权限集,即
open(filename, O_RDWR|O_CREAT, 0666)
0666是一个八进制数,即每一个6对应三个权限位
6 = 读写
7 = rwx
前三位为所有者权限,接下来的三位为组权限,接下来是世界权限 第一个数字 - 代表是文件或目录。 (0 - 文件,d - 目录) 这里我们用 0 表示文件
这是一个典型的陷阱。编译器允许您不使用权限参数,因为当您打开现有文件时,权限位没有意义。但是当你在创建文件时忘记参数时,你会得到一组随机的权限,例如在您的情况下为 0000 (---)。
关于c - 为什么 open() 使用错误的权限创建我的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2245193/