Home > front end >  Can't make changes and save to output file in C
Can't make changes and save to output file in C

Time:04-10

I have a subject where I'm asked to read a c file,convert it's comments from lowercase to uppercase and vice-versa and then save this file with any changes made to another c file(a blank ouput file for example).I have made a code but It doesn't make any changes to comments,instead it saves the original file to the output.c file,any suggestions?

https://i.stack.imgur.com/6rkvq.png

CodePudding user response:

You are reading in each line into str and modifying it inside the while loop. However, you are never writing that modified content to the new file or saving it anywhere.

There are a couple ways you could do this. I would recommend writing each line inside the while loop.

CodePudding user response:

Try this:

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

int main(){
    char ch;

    FILE *fp1, *fp2;
    char source_file[] = "input2.c";
    char target_file[] = "output.c";
    char str[200];
    fp1 = fopen(source_file, "r");
    fp2 = fopen(target_file, "w");

    while(fgets(str,200,fp1) != NULL){
        int flag = 0;
        int l = strlen(str);
        for(int i = 0; i < l-1; i  ){
            if(str[i]=='/' && str[i 1]=='/'){
                for(int j = i 2; j < l; j  ){
                    if (str[j] >= 'A' && str[j]<='Z')
                        str[j] = str[j]   32;
                    else if (str[j] >= 'a' && str[j]<='z')
                        str[j] = str[j] - 32;
                }
                fprintf(fp2,"%s",str);
                flag = 1;
            }
            if(flag == 1)
                break;
        }
    }

    printf("File copied successfully.\n");
    fclose(fp1); 
    fclose(fp2); 

    return 0;
}
  •  Tags:  
  • c
  • Related