0

I'm trying to do a really simple task.

  1. Check if a file exists
  2. If not, make it

the files should be named like : M0 M1 M2 and so on. Here's the code that I've written. It works for M0 after that I get segmentation fault error:

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

int main (){

    unsigned int fileIndex=0;
    char* fileName="M0";
    FILE* recordFile = NULL;
    while((access(fileName,F_OK)!=-1)) {
        fileIndex++;
        sprintf(fileName,"M%d",fileIndex);
        printf("%s\n",fileName);
    }

    recordFile = fopen(fileName,"wb+");

    fclose(recordFile);
    return 0;
}

any idea what I'm doing wrong here? thanks in advance!

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
Engine
  • 5,360
  • 18
  • 84
  • 162

1 Answers1

4

You are writing into a string literal, which is usually stored in read-only memory.

 char* fileName="M0";

Change it to an array that is a copy of the literal to fix the immediate problem.

char fileName[]="M0";

However, you will probably start running into storage issues if you go above 10, so it is probably better to allocate a larger buffer to accomodate larger filename lengths.

char fileName[10] = "M0";
merlin2011
  • 71,677
  • 44
  • 195
  • 329