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

时间:2017-09-17 11:15:05

标签: c file

我尝试使用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()命令,但没有帮助。有人可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

目前还不清楚为什么要打电话给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