[英]How to delete and rename files in C on windows
I am working on program which renames or deletes the files in the file system. 我正在研究重命名或删除文件系统中文件的程序。 I am using C and it works well on linux machine but fails on windows.
我正在使用C,它在Linux机器上运行良好,但在Windows上无法运行。 i use gcc compiler suit.
我使用gcc编译器套件。 and following is the code it does not delete the files from my file system.
以下是它不会从我的文件系统中删除文件的代码。
Thanks in advance 提前致谢
#include<stdio.h>
int main()
{
printf("Program demonstrating file renaming and file deletion. \n");
printf("Enter file name to be deleted : ");
char fdelete[25];
fflush(stdin);
gets(fdelete);
printf("Enter file name to be renamed : ");
char frename[25];
fflush(stdin);
gets(frename);
if (remove(fdelete)!=0)
{
printf("error deleting the file.\n");
}
if(rename("test2.txt",frename)!=0) //test2.txt is the original file
{
printf("eeror renaming the file.\n");
}
return 0;
}
Your code has a lot of problems. 您的代码有很多问题。
char fdelete[25];
This might have been at least close to acceptable 20 years ago, but nowadays the chances of a file name over 25 characters long are pretty high. 这可能至少已接近20年前的可接受水平,但是如今,文件名超过25个字符的可能性非常高。 You probably want to use
FILENAME_MAX
. 您可能要使用
FILENAME_MAX
。
fflush(stdin);
This (calling fflush
with a file opened for input as its argument) gives undefined behavior. 这(使用打开的文件作为输入参数调用
fflush
)会产生未定义的行为。 Just don't do it. 只是不要这样做。
gets(fdelete);
gets
is a serious source of security problems. gets
是安全问题的严重根源。 Never use it. 永远不要使用它。 Use
fgets
instead. 改用
fgets
。
char frename[25];
Same problem as with fdelete
. 与
fdelete
相同的问题。
fflush(stdin);
gets(frename);
Same problems as above. 与上述相同的问题。
All that said, remove
should delete a file provided there are no other links to that file and the name you pass to it is the name of an actual file. 话虽如此,
remove
应该删除一个文件,前提是该文件没有其他链接,并且您传递给它的名称是实际文件的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.