Any functions into which you pass string literals "I am a string literal"
should use char const *
as the type instead of char*
.
If you're going to fix something, fix it right.
Explanation:
You can not use string literals to initialise strings that will be modified, because they are of type const char*
. Casting away the constness to later modify them is undefined behaviour, so you have to copy your const char*
strings char
by char
into dynamically allocated char*
strings in order to modify them.
Example:
#include <iostream>
void print(char* ch);
void print(const char* ch) {
std::cout<<ch;
}
int main() {
print("Hello");
return 0;
}
If the reason you're checking is so you can do something like if file_exists: open_it()
, it's safer to use a try
around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.
If you're not planning to open the file immediately, you can use os.path.isfile
Return True
if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
import os.path
os.path.isfile(fname)
if you need to be sure it's a file.
Starting with Python 3.4, the pathlib
module offers an object-oriented approach (backported to pathlib2
in Python 2.7):
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
# file exists
To check a directory, do:
if my_file.is_dir():
# directory exists
To check whether a Path
object exists independently of whether is it a file or directory, use exists()
:
if my_file.exists():
# path exists
You can also use resolve(strict=True)
in a try
block:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
Best Answer
Well I threw together a test program that ran each of these methods 100,000 times, half on files that existed and half on files that didn't.
Results for total time to run the 100,000 calls averaged over 5 runs,
exists_test0
(ifstream)exists_test1
(FILE fopen)exists_test2
(posix access())exists_test3
(posix stat())The
stat()
function provided the best performance on my system (Linux, compiled withg++
), with a standardfopen
call being your best bet if you for some reason refuse to use POSIX functions.