]> pd.if.org Git - pdclib/blob - functions/stdio/rename.c
Cleaned up the testing a bit.
[pdclib] / functions / stdio / rename.c
1 /* $Id$ */
2
3 /* 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 #include <stdio.h>
10
11 #ifndef REGTEST
12 #include <_PDCLIB_glue.h>
13
14 #include <string.h>
15
16 extern struct _PDCLIB_file_t * _PDCLIB_filelist;
17
18 int rename( const char * old, const char * new )
19 {
20     struct _PDCLIB_file_t * current = _PDCLIB_filelist;
21     while ( current != NULL )
22     {
23         if ( ( current->filename != NULL ) && ( strcmp( current->filename, old ) == 0 ) )
24         {
25             /* File of that name currently open. Do not rename. */
26             return EOF;
27         }
28         current = current->next;
29     }
30     return _PDCLIB_rename( old, new );
31 }
32
33 #endif
34
35 #ifdef TEST
36 #include <_PDCLIB_test.h>
37
38 #include <stdlib.h>
39
40 int main( void )
41 {
42     FILE * file;
43     remove( testfile1 );
44     remove( testfile2 );
45     /* make sure that neither file exists */
46     TESTCASE( fopen( testfile1, "r" ) == NULL );
47     TESTCASE( fopen( testfile2, "r" ) == NULL );
48     /* rename file 1 to file 2 - expected to fail */
49     TESTCASE( rename( testfile1, testfile2 ) == -1 );
50     /* create file 1 */
51     TESTCASE( ( file = fopen( testfile1, "w" ) ) != NULL );
52     TESTCASE( fputs( "x", file ) != EOF );
53     TESTCASE( fclose( file ) == 0 );
54     /* check that file 1 exists */
55     TESTCASE( ( file = fopen( testfile1, "r" ) ) != NULL );
56     TESTCASE( fclose( file ) == 0 );
57     /* rename file 1 to file 2 */
58     TESTCASE( rename( testfile1, testfile2 ) == 0 );
59     /* check that file 2 exists, file 1 does not */
60     TESTCASE( fopen( testfile1, "r" ) == NULL );
61     TESTCASE( ( file = fopen( testfile2, "r" ) ) != NULL );
62     TESTCASE( fclose( file ) == 0 );
63     /* create another file 1 */
64     TESTCASE( ( file = fopen( testfile1, "w" ) ) != NULL );
65     TESTCASE( fputs( "x", file ) != EOF );
66     TESTCASE( fclose( file ) == 0 );
67     /* check that file 1 exists */
68     TESTCASE( ( file = fopen( testfile1, "r" ) ) != NULL );
69     TESTCASE( fclose( file ) == 0 );
70     /* rename file 1 to file 2 - expected to fail, see comment in
71        _PDCLIB_rename() itself.
72     */
73     /* NOREG as glibc overwrites existing destination file. */
74     TESTCASE_NOREG( rename( testfile1, testfile2 ) == -1 );
75     /* remove both files */
76     remove( testfile1 );
77     remove( testfile2 );
78     /* check that they're gone */
79     TESTCASE( fopen( testfile1, "r" ) == NULL );
80     TESTCASE( fopen( testfile2, "r" ) == NULL );
81     return TEST_RESULTS;
82 }
83
84 #endif
85