Я новичок в C программировании. У меня проблемы с записью в файл с помощью функции open () в C, вот мой код для ясности
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
void usage(char *prog_name, char *filename){
printf("Usage: %s <data to add to %s> \n",prog_name, filename);
exit(0);
}
void fatal(char *);
void *errchck_malloc(unsigned int);
int main(int argc, char *argv[]){
int fd; // File descriptor
char *buffer, *datafile;
buffer = (char *) errchck_malloc(100);
datafile = (char *) errchck_malloc(20);
strcpy(datafile, "./simplenote.txt");
if (argc < 2)
usage(argv[0], datafile);
strcpy(buffer, argv[1]);
printf("[DEBUG] buffer @ %p: \'%s\'\n", buffer, buffer);
printf("[DEBUG] datafile @ %p: \'%s\'\n", datafile, datafile);
strncat(buffer, "\n", 1);
// Open file
fd = open(datafile, O_CREAT|O_RDWR,O_APPEND, S_IRUSR, S_IWUSR);
if(fd == -1)
fatal("in main() while opening file");
printf("[DEBUG] file descriptor is %d\n", fd);
// Writing data to file
if(write(fd, buffer, strlen(buffer))==-1)
fatal("in main() while writing buffer to file");
// Closing file
if(close(fd) == -1)
fatal("in main() while closing file");
printf("Note saved\n");
free(buffer);
free(datafile);
}
// fatal(): Function to display error message then exit
void fatal(char *message){
char err_msg[100];
strcpy(err_msg, "[!!] Fatal Error ");
strncat(err_msg, message, 83);
perror(err_msg);
exit(-1);
}
// errchck_malloc(): An error check malloc wrapper function
void *errchck_malloc(unsigned int size){
void *ptr;
ptr = malloc(size);
if(ptr == NULL)
fatal("in errchck_malloc() on memory allocation");
return ptr;
}
Когда я запускаю программу с первой попытки, программа запускается, как и ожидалось.
первый запуск:
user: ./simplenote "Hello, again"
[DEBUG] buffer @ 0x7fafcb4017a0: 'Hello again'
[DEBUG] datafile @ 0x7fafcb401810: './simplenote.txt'
[DEBUG] file descriptor is 3
Note saved
, когда я пытаюсь открыть файл и просмотреть текст, я получаю сообщение об ошибке «Отказано в доступе». когда я пытаюсь открыть файл с помощью sudo, он открывается и текст находится в файле. Когда я запускаю программу во второй раз, я получаю сообщение об ошибке при открытии файла из-за проблем с разрешениями.
второй запуск:
user: ./simplenote "just checking if it is still working"
[DEBUG] buffer @ 0x7face4c017a0: 'just checking if it is still working'
[DEBUG] datafile @ 0x7face4c01810: './simplenote.txt'
[!!] Fatal Error in main() while opening file: Permission denied
Как исправить проблемы с разрешениями при создании файла?