用C语言编程修改文件名(C++也行)

用C语言编程修改文件名(C++也行),第1张

修改文件,可要调用 *** 作系统提供的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.txt\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修改文件名:使用rename函数。

rename函数:功能描述: 改变文件的名称或者位置,如果目标已存在,将被自动覆盖。   用法:  #include <stdio.h>int rename(const char *oldpath, const char *newpath)参数:   

oldpath:旧文件名。 newpath:新文件名或者新位置。 

具体可以分以下2种情况:

1、修改单个文件

    直接使用rename即可。

2、批量修改文件(如:按一定规则修改某目录下所有文件)

    需要使用opendir遍历目录,然后修改该目录下文件。下面提供一个简单的例子。

void ModFilesName(const char *pcszPath)

{

    char szPathFile[1024] = {0}                            //路径+文件名

    DIR *dir_p

    struct dirent *direntp

    struct stat entryInfo

    //文件目录不存在,则创建

    if(stat(pcszPath, &entryInfo) < 0)

    {

        printf("Auto create folder:%s\n", pcszPath)

        mkdir(pcszPath, 0755)

    }

    

    if ((dir_p = opendir (pcszPath)) == NULL)

    {

        return

    }

    while ((direntp = readdir (dir_p)) != NULL)

    {

        //组合完整路径

        sprintf(szPathFile, "%s/%s", pcszPath, direntp->d_name)

        

        //判断文件是否是目录

        if(lstat(szPathFile, &entryInfo) == 0)

        {

            if(S_ISDIR(entryInfo.st_mode))

            {

                continue                                   //忽略目录

            }

            

            rename(szPathFile, 你要修改成的文件名)

        }

    } // while ( ...

    

    closedir (dir_p)

}

    

推荐一片文章:http://blog.chinaunix.net/uid-7525568-id-251530.html

希望能帮助到你,你的好评是我前进的动力!谢谢!

在<stdio.h>包里有两个函数可以满足你的要求:

注意,这两个函数 *** 作的文件必须要关闭,否则会执行失败,如果失败,执行完成后可以通过比较errno的值来确定失败原因.

重命名:

int rename(const char *oldname, const char *newname)

参数解释:

oldname:原文件名

newname:新文件名(可以指定全局路径来移动文件)

返回值:

0:成功

-1:失败,并将全局变量errno置为错误码

删除:

int remove(const char *filename)

参数解释:

filename:要删除的文件名

返回值:

0:成功

-1:失败,并将全局变量errno置为错误码


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/tougao/12091513.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-21
下一篇2023-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存