如何使用C语言进行文件的重命名及删除 *** 作?

如何使用C语言进行文件的重命名及删除 *** 作?,第1张

在<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置为错游雀孙误码

函数名: rename

功 能: 重命名文件

用樱绝凳 法: int rename(char *oldname, char *newname)

程序例:

#include <stdio.h>

int main(void)

{

char oldname[80], newname[80]

/* prompt for file to rename and new name */

printf("File to rename: ")

gets(oldname)

printf("New name: ")

gets(newname)

/* Rename the file */

if (rename(oldname, newname) == 0)

printf("Renamed %s to %s.\宏歼n", oldname, newname)

else

perror("rename")

return 0

}

--------------------------------------------------------

函数名: remove

功 能: 删除一个文脊旅件

用 法: int remove(char *filename)

程序例:

#include <stdio.h>

int main(void)

{

char file[80]

/* prompt for file name to delete */

printf("File to delete: ")

gets(file)

/* delete the file */

if (remove(file) == 0)

printf("Removed %s.\n",file)

else

perror("remove")

return 0

}

--------------------------------------------------------

拷贝的话,

要么字节写一个函数;

或者使用 win API: CopyFile

--------------------------------------------------------

http://itzs.net/Article/cxsj/fpro/200612/7004.html

--------------------------------------------------------

/* Chapter 1. Basic cp file copy program. C library Implementation. */

/* cp file1 file2: Copy file1 to file2. */

#include <windows.h>

#include <stdio.h>

#include <errno.h>

#define BUF_SIZE 256

int main (int argc, char *argv [])

{

FILE *in_file, *out_file

char rec [BUF_SIZE]

size_t bytes_in, bytes_out

if (argc != 3) {

printf ("Usage: cp file1 file2\n")

return 1

}

in_file = fopen (argv [1], "rb")

if (in_file == NULL) {

perror (argv [1])

return 2

}

out_file = fopen (argv [2], "wb")

if (out_file == NULL) {

perror (argv [2])

return 3

}

/* Process the input file a record at a time. */

while ((bytes_in = fread (rec, 1, BUF_SIZE, in_file)) >0) {

bytes_out = fwrite (rec, 1, bytes_in, out_file)

if (bytes_out != bytes_in) {

perror ("Fatal write error.")

return 4

}

}

fclose (in_file)

fclose (out_file)

return 0

}

呵呵,问题不大其实你就是逻滚伏辑上的问题,你文件还是扮备腔打开的怎么能够重命名或者删除掉呢

你应该先关闭文件才能作上述 *** 作啊,就如我们在厅衫windows系统里面对文件的 *** 作一样

正是!!!


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

原文地址: http://outofmemory.cn/tougao/12195258.html

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

发表评论

登录后才能评论

评论列表(0条)

保存