Please help me. The following program builds and compiles just fine however when I try to execute it it stops before getting any output, displaying "The instruction at "0x77c48a0b" referenced memory at "0x00000014". The memory could not be "read"". I also get the following when the debugger reaches the point where I input for the switch-case variable: "An Access violation (Segmentation fault) is raised in the program."

**I'm practicing files hehe :/

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<cstdlib>

void createFile(char fileName[])
{
    FILE *fp;
    fopen(fileName,"w");
    fclose(fp);
}
void writeFile(char fileName[],char content[])
{
     FILE *fp;
     fopen(fileName,"w");
     if(fp==NULL)
     printf("error 404: file not found");
     else
     {
         fwrite(content,strlen(content),sizeof(content),fp);
         printf("Write your desired content");
         scanf("%s",content);
     }
     fclose(fp);
}

void displayFile(char fileName[],char content[])
{
     FILE *fp;
     char temp[50];
     fopen(fileName,"r");
     if(fp==NULL)
     printf("error 404: file not found");
     else
     {
                 fseek(fp,SEEK_SET,0);
                 fread(temp,strlen(content),sizeof(content),fp);
                 printf("%s\n",temp);
     }
     fclose(fp);
}    
int main()
{
    char a[50], b[50];
    char choice;
    printf("A to create the file, B to write on the file, or C to display the file's content: ");
    scanf("%c",&choice);
    switch(choice)
    {
                  case 'A':{
                       printf("Create the filename: ");
                       scanf("%s",a);
                       fflush(stdin);
                       createFile(a);
                       } break;
                  case 'B': writeFile(a,b); break;
                  case 'C': displayFile(a,b); break;
                  default: break;
    }
    getch();
    system("pause");
    return 0;
}

Edited 2 Years Ago by brent.banaag

You have a pointer, fp, that you create and use but you never, ever set it to anything. It will be pointing to some random location in memory. This is very bad.

This article has been dead for over six months. Start a new discussion instead.