How can I detect if a file exists?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







3















I'm programming in C and trying to write portable code.



My question is, how can I tell if a file exists and is readable?



I am currently using the code:



   f = fopen(filename, "r");
if (f) printf("File exists!");


In my program, filename is set by the user, and should be considered as untrusted input (e.g. filename could be maliciously crafted).



My issue is that the above code is not robust. For example, when used on windows with the filename "PRN" it will print "File exists!" even though no such file exists on the filesystem.



I know I could filter out the reserved filenames on Windows, as there is only about a dozen of them, but that feels like a hack. Also, I only know what I know. Maybe there are other "reserved" or "special" names that I don't know about.



Is there any simple and portable way to determine if a file exists in C?



Alternatively, if I have to use an OS API, which function should I use?










share|improve this question


















  • 2





    Just FYI: Portable code is a myth. There are applications which are ported successfully, but really there is nothing called universally portable.

    – Sourav Ghosh
    Jan 4 at 6:17






  • 3





    Attempting to open the file is one of the most reliable and portable ways to see whether the file can be opened. It typically isn't subject to the TOCTOU (Time Of Check, Time Of Use) attacks that alternatives such as using access() or stat() or lstat() are vulnerable to. And those alternatives are POSIX-specific which may limit their usefulness for you.

    – Jonathan Leffler
    Jan 4 at 6:39






  • 1





    You probably want one of the File Management Functions, and probably one in the GetFileAttributes* family.

    – jxh
    Jan 4 at 6:53






  • 1





    @jim No, fopen doesn't magically succeed when the file doesn't exist. Either the file exist (try to use an absolute path) or your code is brken (then show an MCVE).

    – Tom's
    Jan 4 at 15:07






  • 1





    @Tom's Did you read the question? Windows has reserved filenames. If you use fopen("COM1.jpg", "r") on Windows, it will open a pipe to a serial port. The file COM1.jpg does not (and indeed isn't allow to) exist as an actual file.

    – jim
    Jan 4 at 16:12


















3















I'm programming in C and trying to write portable code.



My question is, how can I tell if a file exists and is readable?



I am currently using the code:



   f = fopen(filename, "r");
if (f) printf("File exists!");


In my program, filename is set by the user, and should be considered as untrusted input (e.g. filename could be maliciously crafted).



My issue is that the above code is not robust. For example, when used on windows with the filename "PRN" it will print "File exists!" even though no such file exists on the filesystem.



I know I could filter out the reserved filenames on Windows, as there is only about a dozen of them, but that feels like a hack. Also, I only know what I know. Maybe there are other "reserved" or "special" names that I don't know about.



Is there any simple and portable way to determine if a file exists in C?



Alternatively, if I have to use an OS API, which function should I use?










share|improve this question


















  • 2





    Just FYI: Portable code is a myth. There are applications which are ported successfully, but really there is nothing called universally portable.

    – Sourav Ghosh
    Jan 4 at 6:17






  • 3





    Attempting to open the file is one of the most reliable and portable ways to see whether the file can be opened. It typically isn't subject to the TOCTOU (Time Of Check, Time Of Use) attacks that alternatives such as using access() or stat() or lstat() are vulnerable to. And those alternatives are POSIX-specific which may limit their usefulness for you.

    – Jonathan Leffler
    Jan 4 at 6:39






  • 1





    You probably want one of the File Management Functions, and probably one in the GetFileAttributes* family.

    – jxh
    Jan 4 at 6:53






  • 1





    @jim No, fopen doesn't magically succeed when the file doesn't exist. Either the file exist (try to use an absolute path) or your code is brken (then show an MCVE).

    – Tom's
    Jan 4 at 15:07






  • 1





    @Tom's Did you read the question? Windows has reserved filenames. If you use fopen("COM1.jpg", "r") on Windows, it will open a pipe to a serial port. The file COM1.jpg does not (and indeed isn't allow to) exist as an actual file.

    – jim
    Jan 4 at 16:12














3












3








3








I'm programming in C and trying to write portable code.



My question is, how can I tell if a file exists and is readable?



I am currently using the code:



   f = fopen(filename, "r");
if (f) printf("File exists!");


In my program, filename is set by the user, and should be considered as untrusted input (e.g. filename could be maliciously crafted).



My issue is that the above code is not robust. For example, when used on windows with the filename "PRN" it will print "File exists!" even though no such file exists on the filesystem.



I know I could filter out the reserved filenames on Windows, as there is only about a dozen of them, but that feels like a hack. Also, I only know what I know. Maybe there are other "reserved" or "special" names that I don't know about.



Is there any simple and portable way to determine if a file exists in C?



Alternatively, if I have to use an OS API, which function should I use?










share|improve this question














I'm programming in C and trying to write portable code.



My question is, how can I tell if a file exists and is readable?



I am currently using the code:



   f = fopen(filename, "r");
if (f) printf("File exists!");


In my program, filename is set by the user, and should be considered as untrusted input (e.g. filename could be maliciously crafted).



My issue is that the above code is not robust. For example, when used on windows with the filename "PRN" it will print "File exists!" even though no such file exists on the filesystem.



I know I could filter out the reserved filenames on Windows, as there is only about a dozen of them, but that feels like a hack. Also, I only know what I know. Maybe there are other "reserved" or "special" names that I don't know about.



Is there any simple and portable way to determine if a file exists in C?



Alternatively, if I have to use an OS API, which function should I use?







c windows filesystems






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 4 at 6:16









jimjim

192




192








  • 2





    Just FYI: Portable code is a myth. There are applications which are ported successfully, but really there is nothing called universally portable.

    – Sourav Ghosh
    Jan 4 at 6:17






  • 3





    Attempting to open the file is one of the most reliable and portable ways to see whether the file can be opened. It typically isn't subject to the TOCTOU (Time Of Check, Time Of Use) attacks that alternatives such as using access() or stat() or lstat() are vulnerable to. And those alternatives are POSIX-specific which may limit their usefulness for you.

    – Jonathan Leffler
    Jan 4 at 6:39






  • 1





    You probably want one of the File Management Functions, and probably one in the GetFileAttributes* family.

    – jxh
    Jan 4 at 6:53






  • 1





    @jim No, fopen doesn't magically succeed when the file doesn't exist. Either the file exist (try to use an absolute path) or your code is brken (then show an MCVE).

    – Tom's
    Jan 4 at 15:07






  • 1





    @Tom's Did you read the question? Windows has reserved filenames. If you use fopen("COM1.jpg", "r") on Windows, it will open a pipe to a serial port. The file COM1.jpg does not (and indeed isn't allow to) exist as an actual file.

    – jim
    Jan 4 at 16:12














  • 2





    Just FYI: Portable code is a myth. There are applications which are ported successfully, but really there is nothing called universally portable.

    – Sourav Ghosh
    Jan 4 at 6:17






  • 3





    Attempting to open the file is one of the most reliable and portable ways to see whether the file can be opened. It typically isn't subject to the TOCTOU (Time Of Check, Time Of Use) attacks that alternatives such as using access() or stat() or lstat() are vulnerable to. And those alternatives are POSIX-specific which may limit their usefulness for you.

    – Jonathan Leffler
    Jan 4 at 6:39






  • 1





    You probably want one of the File Management Functions, and probably one in the GetFileAttributes* family.

    – jxh
    Jan 4 at 6:53






  • 1





    @jim No, fopen doesn't magically succeed when the file doesn't exist. Either the file exist (try to use an absolute path) or your code is brken (then show an MCVE).

    – Tom's
    Jan 4 at 15:07






  • 1





    @Tom's Did you read the question? Windows has reserved filenames. If you use fopen("COM1.jpg", "r") on Windows, it will open a pipe to a serial port. The file COM1.jpg does not (and indeed isn't allow to) exist as an actual file.

    – jim
    Jan 4 at 16:12








2




2





Just FYI: Portable code is a myth. There are applications which are ported successfully, but really there is nothing called universally portable.

– Sourav Ghosh
Jan 4 at 6:17





Just FYI: Portable code is a myth. There are applications which are ported successfully, but really there is nothing called universally portable.

– Sourav Ghosh
Jan 4 at 6:17




3




3





Attempting to open the file is one of the most reliable and portable ways to see whether the file can be opened. It typically isn't subject to the TOCTOU (Time Of Check, Time Of Use) attacks that alternatives such as using access() or stat() or lstat() are vulnerable to. And those alternatives are POSIX-specific which may limit their usefulness for you.

– Jonathan Leffler
Jan 4 at 6:39





Attempting to open the file is one of the most reliable and portable ways to see whether the file can be opened. It typically isn't subject to the TOCTOU (Time Of Check, Time Of Use) attacks that alternatives such as using access() or stat() or lstat() are vulnerable to. And those alternatives are POSIX-specific which may limit their usefulness for you.

– Jonathan Leffler
Jan 4 at 6:39




1




1





You probably want one of the File Management Functions, and probably one in the GetFileAttributes* family.

– jxh
Jan 4 at 6:53





You probably want one of the File Management Functions, and probably one in the GetFileAttributes* family.

– jxh
Jan 4 at 6:53




1




1





@jim No, fopen doesn't magically succeed when the file doesn't exist. Either the file exist (try to use an absolute path) or your code is brken (then show an MCVE).

– Tom's
Jan 4 at 15:07





@jim No, fopen doesn't magically succeed when the file doesn't exist. Either the file exist (try to use an absolute path) or your code is brken (then show an MCVE).

– Tom's
Jan 4 at 15:07




1




1





@Tom's Did you read the question? Windows has reserved filenames. If you use fopen("COM1.jpg", "r") on Windows, it will open a pipe to a serial port. The file COM1.jpg does not (and indeed isn't allow to) exist as an actual file.

– jim
Jan 4 at 16:12





@Tom's Did you read the question? Windows has reserved filenames. If you use fopen("COM1.jpg", "r") on Windows, it will open a pipe to a serial port. The file COM1.jpg does not (and indeed isn't allow to) exist as an actual file.

– jim
Jan 4 at 16:12












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54033897%2fhow-can-i-detect-if-a-file-exists%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54033897%2fhow-can-i-detect-if-a-file-exists%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Mossoró

Error while reading .h5 file using the rhdf5 package in R

Pushsharp Apns notification error: 'InvalidToken'