我试图从一个文件读取一些文本,并写到另一个使用 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;
}