开发者

Changing the File name on local path using C File Handling?

开发者 https://www.devze.com 2023-03-22 12:35 出处:网络
FILE *fp; fp=fopen(\"c:\\\\test.txt\", \"r\"); int fgetc (FILE *fp); int fputc( int c, FILE *fp ); Is there any way to change a filename that already exist in computer?
FILE *fp;
fp=fopen("c:\\test.txt", "r");
int fgetc (FILE *fp);
int fputc( int c, FILE *fp );

Is there any way to change a filename that already exist in computer? If yes, then how should i reference the file?? Using pointer we can only reference the contents of the file... so is th开发者_Go百科ere any method which reference the filename??? Here is how i have reference the files in C:


Use the rename function.

if (rename("c:\\test.txt", "c:\\newname.txt") == -1) {
    perror("rename of c:\\test.txt failed");
    exit(EXIT_FAILURE);
}

Edit: As Tomas points out in his answer, you need to #include <stdio.h> as well. See your friendly C reference manual for more information.

Edit: rename is part of the C standard (1989 and 1999 versions both).


#include <stdio.h>

int rename(const char *oldpath, const char *newpath);


POSIX says that rename() returns -1 on failure, but the C standard only says that it returns some non-zero value. (Both say it returns 0 on success.) If you change the comparison from == -1 to != 0, it will work correctly on both POSIX and non-POSIX systems.

Note that #include <stdio.h> provides the declaration for rename(), and for all the other standard I/O functions); trying to declare them yourself is unnecessary and can cause problems.

0

精彩评论

暂无评论...
验证码 换一张
取 消