0

I am creating a C program to convert all lower case to upper case and vice versa. In the C program, I am trying to get a string from a text file and access each of the characters. But my program crashes. What is the error that I am doing here? Below is my code:

 //Program to read contents from a source file and convert the lower case characters to a upper case and vice versa and print it on a target file

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

void merge(FILE *fp,int n,char *fdata,FILE *fpr)
{
    char change_case[1000];
    int loop = 0;

    while(fgets(fdata,n,fp)!=NULL)
    {
        fgets(fdata,n,fp);

        //printf("%s",fdata);

        if ((*(fdata+loop) >= 65) && (*(fdata+loop) <= 90))
        {
            printf("%c",*(fdata+loop));
            change_case[loop] = *(fdata+loop)+32;
        }
        else if ((*(fdata+loop) >= 97) && ((*fdata+loop) <= 122))
        {
            printf("%c",*(fdata+loop));
            change_case[loop] = *(fdata+loop)-32;
        }
        else
        {
            change_case[loop] = *(fdata+loop);
        }
        loop++;

        fpr = fopen("Text File 3.dat","w");

        if (fpr == NULL)
        {
            printf("Error in accessing / writing the target file"); 
        }
        else
        {
            fputs(change_case,fpr);
            printf("Line written successfully : %s\n", change_case);
        }
    }
}

int main()
{
    FILE *sfp, *tfp; //declaring a file pointer for source file and target file
    char *fdata;
    int n = 1000;
    sfp = fopen("Text File 1.txt","r");

    if (sfp == NULL)
    {
        printf("Error in reading the source file\n");
    }

    else
    {
        merge(sfp,n,fdata,tfp);
    }   

    fclose(sfp);

return 0;
}
Kiran C K
  • 3
  • 2

1 Answers1

1

In function void merge(FILE *fp,int n,char *fdata,FILE *fpr)-

fgets(fdata,n,fp);         // you tend to write at invalid location 

memory is not allocated to fdata . You need to allocate memory to it .

fdata=malloc(n);     // check its return and also remember to free it

Note - Don't use while!feof(fp) .

You can do this instead -

while(fgets(fdata,n,fp)!=NULL)
{
     // your code
}
Community
  • 1
  • 1
ameyCU
  • 16,489
  • 2
  • 26
  • 41