【发布时间】:2011-01-15 18:08:12
【问题描述】:
我正在尝试从一个文件中读取一些文本并使用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',一切都会重新开始正常工作。
有人可以让我知道我在公开电话中哪里出了问题吗?
谢谢!
下面我贴了完整的程序供大家参考:
#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;
}
【问题讨论】:
-
你可能不需要777权限;您可能最多只需要 666,而且通常您也不需要公共写权限。您不希望人们执行您的数据文件。