]> pd.if.org Git - pdclib/blob - functions/stdio/rename.c
Whitespace cleanups.
[pdclib] / functions / stdio / rename.c
1 /* 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
11 #include "_PDCLIB_glue.h"
12
13 #include <string.h>
14
15 extern struct _PDCLIB_file_t * _PDCLIB_filelist;
16
17 int rename( const char * old, const char * new )
18 {
19     struct _PDCLIB_file_t * current = _PDCLIB_filelist;
20     while ( current != NULL )
21     {
22         if ( ( current->filename != NULL ) && ( strcmp( current->filename, old ) == 0 ) )
23         {
24             /* File of that name currently open. Do not rename. */
25             return EOF;
26         }
27         current = current->next;
28     }
29     return _PDCLIB_rename( old, new );
30 }
31
32 #endif
33
34 #ifdef TEST
35
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     TESTCASE( remove( testfile1 ) == 0 );
77     TESTCASE( remove( testfile2 ) == 0 );
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