Talk:Check that file exists: Difference between revisions

From Rosetta Code
Content added Content deleted
m (moved Talk:Ensure that a file exists to Talk:Check that file exists: we are checking not ensuring)
No edit summary
Line 46: Line 46:
I think this should be named "Check if file exists". I think we are checking, rather than ensuring. "Ensure" implies creation if file does not exist. [[User:Markhobley|Markhobley]] 20:13, 18 August 2011 (UTC)
I think this should be named "Check if file exists". I think we are checking, rather than ensuring. "Ensure" implies creation if file does not exist. [[User:Markhobley|Markhobley]] 20:13, 18 August 2011 (UTC)
:That seems fine. --[[User:Mwn3d|Mwn3d]] 20:35, 18 August 2011 (UTC)
:That seems fine. --[[User:Mwn3d|Mwn3d]] 20:35, 18 August 2011 (UTC)


==Extra credits==

Would it be possible to add a "Extra credits" for the test to make sure that a directory called input.txt is not identified as a file, and vice versa for docs? Or to just add it as a clarification. --Bengt Mon May 27 08:48:26 CEST 2013

Revision as of 06:54, 27 May 2013

Old solution for C

<lang c>#include<stdio.h>

  1. include<dir.h>
  2. include<errno.h>

signed int fexist(char*s){

FILE*f=fopen(s,"r");
if(!f)return (errno==ENOENT)-1;
fclose(f);
return 1;

}

signed int direxist(char*s){

if(chdir(s))return (errno==ENOENT)-1;
return 1;

}

void report(char*name,signed int r){

char*s="might";
if(r>0)s="does";
else if(!r)s="does not";
printf("%s %s exist.\r\n",name,s);

}

void chkfile(char*s){

report(s,fexist(s));

}

void chkdir(char*s){

report(s,direxist(s));

}

int main(){

chkfile("input.txt");
chkfile("/input.txt");
chkdir("docs");
chkdir("/docs");
return 0;

}</lang>

This used chdir() from POSIX to test a directory. I got compiler error, because OpenBSD has no <dir.h>; I must use <unistd.h>. I also got "input.txt does exist" when input.txt was a directory, because BSD can fopen() a directory. The current solution for C uses S_ISREG() and S_ISDIR() from POSIX. --Kernigh 00:59, 18 May 2011 (UTC)

Rename

I think this should be named "Check if file exists". I think we are checking, rather than ensuring. "Ensure" implies creation if file does not exist. Markhobley 20:13, 18 August 2011 (UTC)

That seems fine. --Mwn3d 20:35, 18 August 2011 (UTC)


Extra credits

Would it be possible to add a "Extra credits" for the test to make sure that a directory called input.txt is not identified as a file, and vice versa for docs? Or to just add it as a clarification. --Bengt Mon May 27 08:48:26 CEST 2013