简体   繁体   中英

how to create a textfile in a given path if the file doesn't exist

void my_create(char* path)
{
    FILE* fp;
    fp = fopen(path, "rb+");
    if (fp == NULL) /* File doesn't exist*/ 
        fp = fopen(path, "wb");
}

Why doesn't it work ? or am I doing something wrong by given wrong path ? Not so sure.

Thanks in advance

File name may be unacceptable or you live a permission problem.

Try this :

#include <string.h>
#include <errno.h>

void my_create(char* path)
{
    FILE* fp;
    fp = fopen(path, "rb+");
    if (fp == NULL) { /* File doesn't exist*/ 
        printf ("File does not exist : %s", path)
        fp = fopen(path, "wb+");
        if (fp == NULL) {
            fprintf (stderr, "Cannot create file : %s\n", path);
            fprintf (stderr, "Reason : %s" , strerror (errno));
        }
    }
}

I dont think checking file exists or not with fopen is the correct way. You can use stat().

struct stat st = {0};
if (stat(path, &st) == -1) 
{
    FILE *fp = fopen(path, "w+");
    if (!fp) printf("Can not create file: %d\n", errno);
    else fclose(fp); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM