Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file in Linux using C

Tags:

I am trying to create a write only file in C on Linux (Ubuntu). This is my code:

 int fd2 = open ("/tmp/test.svg", O_RDWR|O_CREAT);   if (fd2 != -1) {    //....  } 

But why do the files I created have 'xr' mode? How can I create it so that I can open it myself at command prompt?

------xr--  1 michael michael  55788 2010-03-06 21:57 test.txt* ------xr--  1 michael michael   9703 2010-03-06 22:41 test.svg* 
like image 473
michael Avatar asked Mar 07 '10 07:03

michael


People also ask

What is create () in C?

1. Create: Used to Create a new empty file. Syntax in C language: int create(char *filename, mode_t mode) Parameter: filename : name of the file which you want to create.

How do I save a file in C?

Press ctrl+f on the keyboard to open file menu. Scroll down to save the option of the file menu using the down arrow key of the keyboard and press enter. This will open the save file dialog box. Pressing F2 key on the keyboard will also open the save file dialog box of the Turbo C.


1 Answers

You need the three-argument form of open() when you specify O_CREAT. When you omit the third argument, open() uses whatever value happens to be on the stack where the third argument was expected; this is seldom a coherent set of permissions (in your example, it appears that decimal 12 = octal 014 was on the stack).

The third argument is the permissions on the file - which will be modified by the umask() value.

int fd2 = open("/tmp/test.svg", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH); 

Note that you can create a file without write permissions (to anyone else, or any other process) while still being able to write to it from the current process. There is seldom a need to use execute bits on files created from a program - unless you are writing a compiler (and '.svg' files are not normally executables!).

The S_xxxx flags come from <sys/stat.h> and <fcntl.h> — you can use either header to get the information (but open() itself is declared in <fcntl.h>).

Note that the fixed file name and the absence of protective options such as O_EXCL make even the revised open() call somewhat unsafe.

like image 173
Jonathan Leffler Avatar answered Dec 01 '22 18:12

Jonathan Leffler