gpt4 book ai didi

C - 无法使用remove()删除文件夹中的文件

转载 作者:行者123 更新时间:2023-11-30 19:33:08 33 4
gpt4 key购买 nike

我正在尝试使用 C 删除文件夹中的文件,但它崩溃了并给我一些返回值

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
FILE *fp1;
char str[100];
gets(str);
strcat(str,"txt");

fp1 = fopen(str,"r");
fclose(fp1);

remove(str);

return 0;
}

这不起作用。我正在使用 Windows XP SP2(32 位),并且还在 C 程序中尝试了 system() 命令,但没有帮助。有人可以帮忙解决这个问题吗?

最佳答案

目前尚不清楚您为何调用 fopen,您没有从中读取任何内容。如果您尝试使用它来检查文件是否存在,则没有必要,remove 的返回结果将告诉您删除是否成功。

例如,您可以执行以下操作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

#define EXT ".txt"

#ifndef PATH_MAX
#define PATH_MAX 4096
#endif

int main (void) {

char buf[PATH_MAX] = "";
size_t len = 0;

printf ("enter filename to delete (without .txt); ");
if (!fgets (buf, sizeof buf, stdin) || *buf == '\n') {
fprintf (stderr, "error: EOF or invalid input.\n");
return 1;
}

len = strlen (buf); /* get length */
if (buf[len - 1] == '\n') /* check trailing '\n' */
buf[--len] = 0; /* overwrite with '\0' */
else {
/* handle error, input exceeded buf size */
return 1;
}

strcat (buf, EXT);

errno = 0;
if (remove (buf) == -1)
perror ("remove failed");
else
printf ("file: '%s' successfully removed.\n", buf);

return 0;
}

示例使用/输出

$ ls -al foobar.txt
-rw-r--r-- 1 david david 0 Sep 17 06:35 foobar.txt

$ ./bin/rmfile
enter filename to delete (without .txt); foobar
file: 'foobar.txt' successfully removed.

$ ./bin/rmfile
enter filename to delete (without .txt); foobar
remove failed: No such file or directory

它在 Linux 或 DOS 上的工作方式相同(您只需在 Windows 上定义 PATH_MAX)。

Windows 上的使用/输出示例

c:\Users\david\Documents\dev\src-c\tmp>cl /Wall /Ox /Febin\rmfile rmfile.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.

rmfile.c
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation. All rights reserved.

/out:bin\rmfile.exe
rmfile.obj

c:\Users\david\Documents\dev\src-c\tmp>echo "test on Windoze" > foobar.txt

c:\Users\david\Documents\dev\src-c\tmp>dir foobar.txt
Volume in drive C has no label.
Volume Serial Number is 2045-D579

Directory of c:\Users\david\Documents\dev\src-c\tmp

09/17/2017 06:56 AM 20 foobar.txt
1 File(s) 20 bytes
0 Dir(s) 20,235,399,168 bytes free

c:\Users\david\Documents\dev\src-c\tmp>bin\rmfile
enter filename to delete (without .txt); foobar
file: 'foobar.txt' successfully removed.

c:\Users\david\Documents\dev\src-c\tmp>bin\rmfile
enter filename to delete (without .txt); foobar
remove failed: No such file or directory

我想如果您使用的是 Windows,您可能应该在文件顶部定义以下内容,以从编译器中删除 strcat 警告:

#if defined (_WIN32) || defined (_WIN64)
#define _CRT_SECURE_NO_WARNINGS
#endif

关于C - 无法使用remove()删除文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46263465/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com