]> pd.if.org Git - pdclib/blob - platform/posix/functions/_PDCLIB/_PDCLIB_rename.c
Explicit include path removed.
[pdclib] / platform / posix / functions / _PDCLIB / _PDCLIB_rename.c
1 /* _PDCLIB_rename( const char *, const char * )
2
3    This file is part of the Public Domain C Library (PDCLib).
4    Permission is granted to use, modify, and / or redistribute at will.
5 */
6
7 #include <stdio.h>
8
9 #ifndef REGTEST
10 #include "_PDCLIB_glue.h"
11
12 #include <errno.h>
13
14 extern int unlink( const char * pathname );
15 extern int link( const char * old, const char * new );
16
17 int _PDCLIB_rename( const char * old, const char * new )
18 {
19     /* Note that the behaviour if new file exists is implementation-defined.
20        There is nothing wrong with either overwriting it or failing the
21        operation, but you might want to document whichever you chose.
22        This example fails if new file exists.
23     */
24     if ( link( old, new ) == 0 )
25     {
26         if ( unlink( old ) == EOF )
27         {
28             return -1;
29         }
30         else
31         {
32             return 0;
33         }
34     }
35     else
36     {
37         return EOF;
38     }
39 }
40
41 #endif
42
43 #ifdef TEST
44 #include "_PDCLIB_test.h"
45
46 #include <stdlib.h>
47
48 int main( void )
49 {
50 #ifndef REGTEST
51     FILE * file;
52     remove( testfile1 );
53     remove( testfile2 );
54     /* check that neither file exists */
55     TESTCASE( fopen( testfile1, "r" ) == NULL );
56     TESTCASE( fopen( testfile2, "r" ) == NULL );
57     /* rename file 1 to file 2 - expected to fail */
58     TESTCASE( _PDCLIB_rename( testfile1, testfile2 ) == -1 );
59     /* create file 1 */
60     TESTCASE( ( file = fopen( testfile1, "w" ) ) != NULL );
61     TESTCASE( fputc( 'x', file ) == 'x' );
62     TESTCASE( fclose( file ) == 0 );
63     /* check that file 1 exists */
64     TESTCASE( ( file = fopen( testfile1, "r" ) ) != NULL );
65     TESTCASE( fclose( file ) == 0 );
66     /* rename file 1 to file 2 */
67     TESTCASE( _PDCLIB_rename( testfile1, testfile2 ) == 0 );
68     /* check that file 2 exists, file 1 does not */
69     TESTCASE( fopen( testfile1, "r" ) == NULL );
70     TESTCASE( ( file = fopen( testfile2, "r" ) ) != NULL );
71     TESTCASE( fclose( file ) == 0 );
72     /* create another file 1 */
73     TESTCASE( ( file = fopen( testfile1, "w" ) ) != NULL );
74     TESTCASE( fputc( 'x', file ) == 'x' );
75     TESTCASE( fclose( file ) == 0 );
76     /* check that file 1 exists */
77     TESTCASE( ( file = fopen( testfile1, "r" ) ) != NULL );
78     TESTCASE( fclose( file ) == 0 );
79     /* rename file 1 to file 2 - expected to fail, see comment in
80        _PDCLIB_rename() itself.
81     */
82     TESTCASE( _PDCLIB_rename( testfile1, testfile2 ) == -1 );
83     /* remove both files */
84     remove( testfile1 );
85     remove( testfile2 );
86 #endif
87     return TEST_RESULTS;
88 }
89
90 #endif