malloc
malloc

Reputation: 21

How can I only create a file without opening it

I've been trying to create a file without using system commands. This code I wrote has multiple problems, If i create fptr in the start and check it for NULLity then the double free or corruption occurs, otherwise this way it gives memory dump. Even through previous method I wasnt closing file more than once but I think there's something very simple hiding between the lines I cant see.

int main()
{
    char* filename;
    char x;
    cout << "enter filename.**: ";
    cin >> filename;
    struct stat buffer;
    if (! stat (filename, &buffer))
    {
         cout << ("It exists\n");
    }
    else
    {  
         FILE* fptr;    
         fptr = fopen (filename,"w");;
         fclose (fptr);
    }
}

Really Appreciate your help! :)

Upvotes: 1

Views: 2031

Answers (1)

John Zwinck
John Zwinck

Reputation: 249263

You can use mknod() on some systems (such as Linux; note this is not portable to all operating systems).

if (mknod(filename, S_IFREG|0666, 0) != 0) {
    throw std::system_error(errno, std::system_category());
}

In portable code you will have to open a file in order to create it.

Upvotes: 2

Related Questions