怎么用C语言更改一个已知文件的扩展名?

来源:百度知道 编辑:UC知道 时间:2024/06/22 14:22:13
比如有一个a.txt的文件,怎么把它改成a.bat?最好把C++的方法也顺便介绍一下。

修改文件扩展名,可要调用操作系统提供的API函数,比如Windows上的MoveFile(),也可以直接调用cmd中已提供的重命名命令——rename。下面的示例代码,调用rename命令来重名命文件名。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int ac, char *pav[])
{
if (ac!=3) {
printf("程序名 要重命名的文件路径 新的文件名\n");
printf("示例:test.exe 1.txt 2.bat\n");
return 0;
}
if (access(pav[1], 0) !=0) {
printf("不存在该文件\n");
return 0;
}
char szcmd[256] = "cmd /c rename ";
strcat(szcmd, pav[1] );
strcat(szcmd, " ");
strcat(szcmd, pav[2]);
system(szcmd);
return 0;
}

C,C++
调用 system():

system("REN a.txt a.bat");

若有路径:
system("REN C:\\\\temp\\a.txt C:\\\\temp\\a.bat");

system("ren a.txt a.bat")

System这个好强大