dimanche 29 avril 2018

if file doesn't exits create and write in C

I want to create a file if it doesn't exist and write on it if it's already exists.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 30

int main() {
    FILE * shelfFile;
    //if file doesn't exist
    char start[MAX] = "NULL";
    if (!(shelfFile = fopen("shelf.txt", "r"))) {
        shelfFile = fopen("shelf.txt", "w");
        printf("In if block\n");
        fwrite(start, sizeof(char), MAX, shelfFile);
        fwrite("\n", sizeof(char), 1, shelfFile);
    }   
    fclose(shelfFile);

    system("PAUSE");
    return 0;
}

when I run this code, the file has not been created and printf doesn't work too. Shortly it doesn't enter in if code block. What is wrong with this?

Aucun commentaire:

Enregistrer un commentaire