Check that file exists: Difference between revisions

Content added Content deleted
(Added BBC BASIC)
(→‎{{header|C}}: Fix first example to use filenames from task description.)
Line 209: Line 209:


=={{header|C}}==
=={{header|C}}==
{{works with|POSIX}}
{{libheader|POSIX}}
<lang c>#include <sys/types.h>
<lang c>#include <sys/types.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <unistd.h>

int main(){
/* Check for regular file. */
struct stat file_stat;
int check_reg(const char *path) {
if(stat("/tmp/test",&file_stat) ==0)
struct stat sb;
printf("file exists");
return stat(path, &sb) == 0 && S_ISREG(sb.st_mode);
else
}
printf("no file lol");

return 0;
/* Check for directory. */
int check_dir(const char *path) {
struct stat sb;
return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}

int main() {
printf("input.txt is a regular file? %s\n",
check_reg("input.txt") ? "yes" : "no");
printf("docs is a directory? %s\n",
check_dir("docs") ? "yes" : "no");
printf("/input.txt is a regular file? %s\n",
check_reg("/input.txt") ? "yes" : "no");
printf("/docs is a directory? %s\n",
check_dir("/docs") ? "yes" : "no");
return 0;
}</lang>
}</lang>