我正在尝试创建一个共享文件,该文件必须是int。
int f;
然而,当我到达
时if ((fstat(f, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode)))
它给了我一个错误。该文件必须包含如下字符串:
abcd
我的猜测如下,但不起作用:
int main() {
int f;
void *memoria = NULL;
int tam;
struct stat stbuf;
char string[15] = {0};
f = open("fichero.txt", O_RDWR, S_IRUSR);
// ERROR IS HERE!!
if ((fstat(f, &stbuf) != 0) || (!S_ISREG(stbuf.st_mode))) {
printf("Error");
}
tam = stbuf.st_size;
printf("%d\n", tam);
// Proyect the file
memoria = mmap(0, tam, PROT_WRITE, MAP_SHARED, f, 0);
// Copy the string into the file
memcpy(memoria, "abcd", 5);
munmap(memoria, tam);
return 0;
}
我应该在打开时更改参数吗? 我究竟做错了什么?谢谢!
答案 0 :(得分:0)
如果文件不存在,您需要使用O_CREAT
模式创建文件。
f = open("fichero.txt", O_RDWR | O_CREAT, S_IRUSR);
您应该检查来自open()
的错误:
if (f == -1) {
perror("open");
exit(1);
}