]> pd.if.org Git - pdclib/blob - platform/example/functions/_PDCLIB/rename.c
Added testdriver for _PDCLIB_rename().
[pdclib] / platform / example / functions / _PDCLIB / rename.c
1 /* $Id$ */
2
3 /* _PDCLIB_rename( const char *, const char * )
4
5    This file is part of the Public Domain C Library (PDCLib).
6    Permission is granted to use, modify, and / or redistribute at will.
7 */
8
9 #ifndef REGTEST
10 #include <unistd.h>
11 #include <_PDCLIB_glue.h>
12
13 int _PDCLIB_rename( const char * old, const char * new )
14 {
15     /* Note that the behaviour if new file exists is implementation-defined.
16        There is nothing wrong with either overwriting it or failing the
17        operation, but you might want to document whichever you chose.
18        This example fails if new file exists.
19     */
20     if ( link( old, new ) == 0 )
21     {
22         return unlink( old );
23     }
24     else
25     {
26         return -1;
27     }
28 }
29
30 #endif
31
32 #ifdef TEST
33 /* TODO: Work around the following undef */
34 #undef SEEK_SET
35 #include <_PDCLIB_test.h>
36
37 #include <stdlib.h>
38
39 int main( void )
40 {
41     char filename1[ L_tmpnam + 6 ] = "touch ";
42     char filename2[ L_tmpnam ];
43     tmpnam( filename1 + 6 );
44     tmpnam( filename2);
45     /* check that neither file exists */
46     TESTCASE( fopen( filename1 + 6, "r" ) == NULL );
47     TESTCASE( fopen( filename2, "r" ) == NULL );
48     /* rename file 1 to file 2 - expected to fail */
49     TESTCASE( _PDCLIB_rename( filename1 + 6, filename2 ) == -1 );
50     /* create file 1 */
51     system( filename1 );
52     /* check that file 1 exists */
53     TESTCASE( fopen( filename1 + 6, "r" ) != NULL );
54     /* rename file 1 to file 2 */
55     TESTCASE( _PDCLIB_rename( filename1 + 6, filename2 ) == 0 );
56     /* check that file 2 exists, file 1 does not */
57     TESTCASE( fopen( filename1 + 6, "r" ) == NULL );
58     TESTCASE( fopen( filename2, "r" ) != NULL );
59     /* create another file 1 */
60     system( filename1 );
61     /* check that file 1 exists */
62     TESTCASE( fopen( filename1 + 6, "r" ) != NULL );
63     /* rename file 1 to file 2 - expected to fail, see comment in
64        _PDCLIB_rename() itself.
65     */
66     TESTCASE( _PDCLIB_rename( filename1 + 6, filename2 ) == -1 );
67     /* remove both files */
68     remove( filename1 + 6 );
69     remove( filename2 );
70     /* check that they're gone */
71     TESTCASE( fopen( filename1 + 6, "r" ) == NULL );
72     TESTCASE( fopen( filename2, "r" ) == NULL );
73     return TEST_RESULTS;
74 }
75
76 #endif