Skip to contentSkip to conversation

Misc C question

DISCUSSION xmp 9 participants 15 messages Jun 20, 2002 – Jun 21, 2002

lore
Share & tools
lore

xmp

author
#0 lore raw

hi, What is the correct unix-style way to check if a file exists ? create it ? and delete it ?. Maybe trying to fopen() it and if call != NULL it exist, else it doesnt?.
I want to know the most standard and used in system such as FreeBSD and solaris, linux.

bye

#1 lore raw

Hi,

Basically, you could use the fexist() function (I think that's what its called), or the way most people do it..
FILE *blah;

if ((blah = fopen("/path/to/file, "r")) != NULL) {
    printf("File does not exist.");
    exit(0);
}

Thanks.
----- Original Message -----
From: "xmp" <[email protected]>
To: <[email protected]>
Sent: Wednesday, June 19, 2002 10:46 PM
Subject: Misc C question

Quoted 1 line

hi, What is the correct unix-style way to check if a file exists ? create

it ? and delete it ?.

Quoted 2 lines

Maybe trying to fopen() it and if call != NULL it exist, else it doesnt?. I want to know the most standard and used in system such as FreeBSD and

solaris, linux.

Quoted 6 lines

bye

-
To unsubscribe from this list: send the line "unsubscribe

linux-c-programming" in

Quoted 3 lines

the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

author
#2 lore raw
Quoted 7 lines

Basically, you could use the fexist() function (I think that's what its called), or the way most people do it..
FILE *blah;

if ((blah = fopen("/path/to/file, "r")) != NULL) {
    printf("File does not exist.");
    exit(0);
}

hi, thanks for reply me.
About your example, What happens if the file exist and you dont have "r" permission? the call will return NULL?.

bye

#3 lore raw

Hi,

"r" is for readonly, if you don't include what it should do with the file, you will get an error on compile. :) The possible options are "r", "w", "r+" "w+", and more. You should consult a book/website which will explain everything you need to know about them :)

Also after you fopen(); you should always fclose(); somewhere after :)

And, no, the call won't return NULL if you don't have "r", it simply won't compile, and can't give you anything ;)

Thanks.
----- Original Message -----
From: "xmp" <[email protected]>
To: "mike" <[email protected]>
Cc: <[email protected]>
Sent: Thursday, June 20, 2002 12:44 AM
Subject: Re: Misc C question

Quoted 9 lines
Quoted 7 lines

Basically, you could use the fexist() function (I think that's what its called), or the way most people do it..
FILE *blah;

if ((blah = fopen("/path/to/file, "r")) != NULL) {
    printf("File does not exist.");
    exit(0);
}

hi, thanks for reply me.
About your example, What happens if the file exist and you dont have "r"

permission? the call will return NULL?.

Quoted 6 lines

bye

-
To unsubscribe from this list: send the line "unsubscribe

linux-c-programming" in

Quoted 3 lines

the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

#4 lore raw

I think we have a mistake here.
It seems that what was asked is whether the file being opened has or not
a read permission.
Yes, your aplication will compile normally and if you don't have read permissions on the file, fopen() will return NULL and set errno. By the way, checking errno is a good way of tracking down errors, try it.

The man page says (both Linux and Solaris):
"Upon successful completion fopen, fdopen and freopen return a FILE pointer. Otherwise, NULL is returned and the global variable errno is set to indicate the error."

see ya

william

Signature · 4 lines
Perl combines all of the worst aspects of BASIC, C and line noise.
                -- Keith Packard

Somebody called 'mike' tried to say something! Take a look:
Quoted 7 lines

Hi,

"r" is for readonly, if you don't include what it should do with the file, you will get an error on compile. :) The possible options are "r", "w", "r+" "w+", and more. You should consult a book/website which will explain everything you need to know about them :)

#5 lore raw
In reply to xmp

Hello xmp,

Thursday, June 20, 2002, 5:46:02 AM, you wrote:

x> hi, What is the correct unix-style way to check if a file exists ? create it ? and delete it ?. x> Maybe trying to fopen() it and if call != NULL it exist, else it doesnt?.
x> I want to know the most standard and used in system such as FreeBSD and solaris, linux.

You should use stat() function:

=========================================================================
stat()
get information about a file or directory

Synopsis:
#include <sys/stat.h>
int stat( const char *path, struct stat *buf );
Description:
The stat() function obtains information about the file or directory referenced in path. This information is placed in the structure located at the address indicated by buf.

--------------------------------------------------------------------------------
This function follows symbolic links and gives you information about the resulting file or directory. If you want information about the link itself, use lstat() instead.

--------------------------------------------------------------------------------

The file <sys/stat.h> contains definitions for the structure stat.

At least the following macros are defined in the <sys/stat.h> header file:

S_ISBLK(m)
Test for block special file.
S_ISCHR(m)
Test for character special file.
S_ISDIR(m)
Test for directory file.
S_ISFIFO(m)
Test for FIFO.
S_ISREG(m)
Test for regular file.
The value m supplied to the macros is the value of the st_mode field of a stat structure. The macro evaluates to a nonzero value if the test is true, and zero if the test is false.

The access permissions for the file or directory are specified as a combination of bits in the st_mode field of a stat structure. These bits are defined in the <sys/stat.h> header file, and are described in the section on this file in the Header Files chapter. The following bits are also encoded in the st_mode field:

S_ISUID
Set user ID on execution. The process's effective user ID is set to that of the owner of the file when the file is run as a program. On a regular file, this bit should be cleared on any write. S_ISGID
Set group ID on execution. Set effective group ID on the process to the file's group when the file is run as a program. On a regular file, this bit should be cleared on any write. Returns:
0
the information was successfully obtained.
-1
the information wasn't successfully obtained.
Errors:
EACCES
Search permission is denied for a component of path.
EIO
A physical error occurred on the block device.
ENAMETOOLONG
The argument path exceeds PATH_MAX in length, or a pathname component is longer than NAME_MAX. These manifests are defined in the <limits.h> header file.
ENOENT
The named file doesn't exist, or path is an empty string.
ENOTDIR
A component of path isn't a directory.
Examples:
#include <stdio.h>
#include <sys/stat.h>

void main()

  {
    struct stat buf;

    if( stat( "file", &buf ) != -1 ) {
      printf( "File size = %d\n", buf.st_size );
    }

}

===================================================================================

Best regards, Oleg O. Ossovitskii
programming engineer, KGPA Ltd.
tel: +7(0112)46-23-40, fax: +7(0112)43-64-96
mailto:[email protected], icq# 33366588

#6 lore raw

Hi,

The simple C function is

	int access(const char *pathname, int mode);

to suit you needs. Read man pages to find out more.

regards...

Signature · 11 lines
**************************************************************************

Mohammed Khalid Ansari                    Tel (res) : 0091-022-3051360
Assistant Manager II                          (off) : 0091-022-2024641
National Centre for Software Technology   Fax       : 0091-022-2049573 
8th flr,Air India Build. Nariman Point,   E-Mail    : [email protected] 	
Mumbai 400021.

Homepage : http://soochak.ncst.ernet.in/~khalid			  	  

**************************************************************************
Quoted 90 lines · Oleg O. Ossovitskii

Hello xmp,

Thursday, June 20, 2002, 5:46:02 AM, you wrote:

x> hi, What is the correct unix-style way to check if a file exists ? create it ? and delete it ?. x> Maybe trying to fopen() it and if call != NULL it exist, else it doesnt?.
x> I want to know the most standard and used in system such as FreeBSD and solaris, linux.

You should use stat() function:

=========================================================================
stat()
get information about a file or directory

Synopsis:
#include <sys/stat.h>
int stat( const char *path, struct stat *buf );
Description:
The stat() function obtains information about the file or directory referenced in path. This information is placed in the structure located at the address indicated by buf.

--------------------------------------------------------------------------------
This function follows symbolic links and gives you information about the resulting file or directory. If you want information about the link itself, use lstat() instead.

--------------------------------------------------------------------------------

The file <sys/stat.h> contains definitions for the structure stat.

At least the following macros are defined in the <sys/stat.h> header file:

S_ISBLK(m)
Test for block special file.
S_ISCHR(m)
Test for character special file.
S_ISDIR(m)
Test for directory file.
S_ISFIFO(m)
Test for FIFO.
S_ISREG(m)
Test for regular file.
The value m supplied to the macros is the value of the st_mode field of a stat structure. The macro evaluates to a nonzero value if the test is true, and zero if the test is false.

The access permissions for the file or directory are specified as a combination of bits in the st_mode field of a stat structure. These bits are defined in the <sys/stat.h> header file, and are described in the section on this file in the Header Files chapter. The following bits are also encoded in the st_mode field:

S_ISUID
Set user ID on execution. The process's effective user ID is set to that of the owner of the file when the file is run as a program. On a regular file, this bit should be cleared on any write. S_ISGID
Set group ID on execution. Set effective group ID on the process to the file's group when the file is run as a program. On a regular file, this bit should be cleared on any write. Returns:
0
the information was successfully obtained.
-1
the information wasn't successfully obtained.
Errors:
EACCES
Search permission is denied for a component of path.
EIO
A physical error occurred on the block device.
ENAMETOOLONG
The argument path exceeds PATH_MAX in length, or a pathname component is longer than NAME_MAX. These manifests are defined in the <limits.h> header file.
ENOENT
The named file doesn't exist, or path is an empty string.
ENOTDIR
A component of path isn't a directory.
Examples:
#include <stdio.h>
#include <sys/stat.h>

void main()

  {
    struct stat buf;

    if( stat( "file", &buf ) != -1 ) {
      printf( "File size = %d\n", buf.st_size );
    }

}

===================================================================================

Best regards, Oleg O. Ossovitskii
programming engineer, KGPA Ltd.
tel: +7(0112)46-23-40, fax: +7(0112)43-64-96
mailto:[email protected], icq# 33366588

-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

#7 lore raw

Hello Mohammed,

Thursday, June 20, 2002, 11:05:58 AM, you wrote:

MKA> The simple C function is

MKA> int access(const char *pathname, int mode);

MKA> to suit you needs. Read man pages to find out more.

access() isn't so useful as stat() because access() use real user ID and real group ID, instead of EUID and EGID.

But You are right - for checking for existense of file access() function is simpler than stat() or lstat().

Best regards, Oleg O. Ossovitskii
programming engineer, KGPA Ltd.
tel: +7(0112)46-23-40, fax: +7(0112)43-64-96
mailto:[email protected], icq# 33366588

#8 lore raw
In reply to xmp
Quoted 2 lines · xmp

hi, What is the correct unix-style way to check if a file exists ? create it ? and delete it ?.

There isn't a "correct" way.

1. You may not be able to tell whether or not the file exists, e.g. because the process has neither read nor execute permission for one or more of the directories in the file's path (or paths; due to hard links, a file may have multiple pathnames).

2. Unless you're using the existence of the file as some sort of "flag", checking for existence is seldom useful. More likely you want to know if it's readable/writable/executable in a particular context (the process' euid/fsuid, egid/fsgid and supplementary gids all affect the result).

3. Functions which return information about the filesystem (e.g. stat/lstat) return information about the past. Just because the file existed (or did not exist) at the time of the check, there's no guarantee that the file still exists (or doesn't exist).

Quoted 2 lines

Maybe trying to fopen() it and if call != NULL it exist, else it doesnt?.

If the file doesn't exist, fopen() will return NULL, but there are plenty of other reasons why fopen() may return NULL.

If you actually intend to read or write the file, the correct approach is to attempt whatever you intend and to handle any failures. You cannot predict in advance whether a given operation will succeed.

If you don't intend to read or write the file, then you shouldn't attempt to open it, as that may have unintended consequences. For files, directories etc it may update the last-accessed time; for device files, the effects vary (e.g. open()ing /dev/st0 device may rewind the tape).

Signature · 1 line
Glynn Clements <[email protected]>
#9 lore raw

hello.
sorry if the message gets duplicated.

I read a while ago of some security issues on doing checks on files before opening, wich is harmfull if the program is suid.

But i dont remember what to do about it.
can someone refresh it to me?
is there anyway you can lock a file access and tell the kernel? and what would happen if the program crashes without unlocking the file?

bye bye

#10 lore raw

Hi

thats because you can check for it.
it disappears and sombody creates a symlink to somewhere like /etc/passwd :)

you need to check it open it and check it again on the open fd

----- Original Message -----
From: "GOMEZ NOGUERA DAVIDEDUARDO" <[email protected]>
To: "Glynn Clements" <[email protected]>
Cc: "xmp" <[email protected]>; <[email protected]>
Sent: Thursday, June 20, 2002 9:42 PM
Subject: Re: Misc C question

Quoted 11 lines

hello.
sorry if the message gets duplicated.

I read a while ago of some security issues on doing checks on files before opening, wich is harmfull if the program is suid.

But i dont remember what to do about it.
can someone refresh it to me?
is there anyway you can lock a file access and tell the kernel? and what would happen if the program crashes without unlocking the file?

Quoted 5 lines

bye bye

-
To unsubscribe from this list: send the line "unsubscribe

linux-c-programming" in

Quoted 2 lines

the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html

#11 lore raw
In reply to GOMEZ NOGUERA DAVIDEDUARDO
Quoted 5 lines · GOMEZ NOGUERA DAVIDEDUARDO

I read a while ago of some security issues on doing checks on files before opening, wich is harmfull if the program is suid.

But i dont remember what to do about it.
can someone refresh it to me?

I presume that you are referring to race conditions, which are a consequence of point 3 of my previous message:

Quoted 4 lines

3. Functions which return information about the filesystem (e.g. stat/lstat) return information about the past. Just because the file existed (or did not exist) at the time of the check, there's no guarantee that the file still exists (or doesn't exist).

A race condition is a situation where the program's behaviour depends upon the timing of certain events.

An example: suppose that a program wants to traverse a directory tree (in the sense of the "find" command, "rm -r", etc). When traversing a directory tree, you need to ignore symbolic links.

A simple approach might look something like this:

	struct stat st;
	...
	if (lstat(filename, &st) < 0)
		error();

	if (S_ISDIR(st.st_mode))
	{
		chdir(filename);
		...
	}

The problem with this is that the directory could be renamed and replaced with a symbolic link between the call to lstat() and the call to chdir(), causing the program to chdir() to wherever the symlink points.

Note that an attacker (someone who is trying to cause a process to malfunction) may be able to force the lstat and/or chdir calls to take a long time by using a combination of deeply nested directories, directories containing a large number of entries, and long "chains" of symbolic links. So, exploiting this type of race condition isn't as difficult as it may seem.

One solution is to perform lstat(".", ...) after the chdir, to check that you changed to the correct directory. This is likely to be safe, as most systems won't let you rename "." or "..".

Quoted 1 line

is there anyway you can lock a file access and tell the kernel?

Unless the OS supports mandatory locking (which is rare), locking a file with flock/lockf/fcntl don't automatically prevent other programs from accessing the file; they only prevent conflicting locks from being obtained.

Similarly, lock files only affect programs which check for the existence of lock files.

Quoted 2 lines

and what would happen if the program crashes without unlocking the file?

Kernel locks are released automatically when the program terminates.

This is the main reason for using kernel locks instead of lock files. The main reasons for using lock files are:

1. They work for device files (/dev/*), and
2. Older NFS implementations don't support kernel locks.

Signature · 1 line
Glynn Clements <[email protected]>
#12 lore raw
Quoted 2 lines · Glynn Clements

2. Older NFS implementations don't support kernel locks.

Hi,

Is there a user-space api for the equivalent of kernel spin-locks?

Signature · 2 lines
thanks,
Chris Quinn
#13 lore raw
In reply to GOMEZ NOGUERA DAVIDEDUARDO
Quoted 5 lines · GOMEZ NOGUERA DAVIDEDUARDO

I read a while ago of some security issues on doing checks on files before opening, wich is harmfull if the program is suid.

But i dont remember what to do about it.
can someone refresh it to me?

I presume that you are referring to race conditions, which are a consequence of point 3 of my previous message:

Quoted 4 lines

3. Functions which return information about the filesystem (e.g. stat/lstat) return information about the past. Just because the file existed (or did not exist) at the time of the check, there's no guarantee that the file still exists (or doesn't exist).

A race condition is a situation where the program's behaviour depends upon the timing of certain events.

An example: suppose that a program wants to traverse a directory tree (in the sense of the "find" command, "rm -r", etc). When traversing a directory tree, you need to ignore symbolic links.

A simple approach might look something like this:

	struct stat st;
	...
	if (lstat(filename, &st) < 0)
		error();

	if (S_ISDIR(st.st_mode))
	{
		chdir(filename);
		...
	}

The problem with this is that the directory could be renamed and replaced with a symbolic link between the call to lstat() and the call to chdir(), causing the program to chdir() to wherever the symlink points.

Note that an attacker (someone who is trying to cause a process to malfunction) may be able to force the lstat and/or chdir calls to take a long time by using a combination of deeply nested directories, directories containing a large number of entries, and long "chains" of symbolic links. So, exploiting this type of race condition isn't as difficult as it may seem.

One solution is to perform lstat(".", ...) after the chdir, to check that you changed to the correct directory. This is likely to be safe, as most systems won't let you rename "." or "..".

Quoted 1 line

is there anyway you can lock a file access and tell the kernel?

Unless the OS supports mandatory locking (which is rare), locking a file with flock/lockf/fcntl don't automatically prevent other programs from accessing the file; they only prevent conflicting locks from being obtained.

Similarly, lock files only affect programs which check for the existence of lock files.

Quoted 2 lines

and what would happen if the program crashes without unlocking the file?

Kernel locks are released automatically when the program terminates.

This is the main reason for using kernel locks instead of lock files. The main reasons for using lock files are:

1. They work for device files (/dev/*), and
2. Older NFS implementations don't support kernel locks.

Signature · 1 line
Glynn Clements <[email protected]>
#14 lore raw
In reply to xmp

Hi

hum would that not be
stat
and
lstat

----- Original Message -----
From: "xmp" <[email protected]>
To: <[email protected]>
Sent: Thursday, June 20, 2002 3:46 AM
Subject: Misc C question

Quoted 1 line

hi, What is the correct unix-style way to check if a file exists ? create

it ? and delete it ?.

Quoted 2 lines

Maybe trying to fopen() it and if call != NULL it exist, else it doesnt?. I want to know the most standard and used in system such as FreeBSD and

solaris, linux.

Quoted 6 lines

bye

-
To unsubscribe from this list: send the line "unsubscribe

linux-c-programming" in

Quoted 2 lines

the body of a message to [email protected]
More majordomo info at http://vger.kernel.org/majordomo-info.html