Search code examples
cdev-c++

How do I get fputc function to work on windows 11?


I'm trying a very simple programm where whatever is written in test.txt gets copied in up.txt but in capital letters. I'm using dev c++ on windows 11 and after running the programm the up.txt file is created but it is empty and i can't figure out why.

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

int main(){
    FILE *fpin, *fpout; 
    char x;
    fpin=fopen("test.txt","r");
    if(fpin==NULL){
        fprintf(stderr,"read error\n");
        exit(666);
    }
    fpout=fopen("up.txt","w");
    if(fpout=NULL){
        fprintf(stderr,"write error/n");
        exit(667);
    }
    while((x=fgetc(fpin))!=EOF){
        fputc(toupper(x),fpout);
    }
    fclose(fpin);
    fclose(fpout);
    
    return 0;
}

I tried the same programm on linux succesfully but i'm not sure why it doesn't work on windows


Solution

  • There is no way this code can work on any platform. Are you sure the code you ran on Linux is actually this exact same code you show in the question?

    The main problem is here:

       fpout=fopen("up.txt","w");
                             // up.txt is now created
    
       if (fpout = NULL) {   // you're using an assignment here (=) instead 
                             // of the == operator
          fprintf(stderr,"write error/n");
          exit(667);
       }
       // fpout is NULL now
    

    if (fpout = NULL) is not a comparision, but it simply assigns NULL to fout. As the result is false (which is more or less the same thing as NULL), fprintf(stderr,"write error/n");exit(667) will not be executed and the program just continues.

    Then in the while loop that follows, you're writing into a NULL FILE pointer, which is undefined behaviour, most likely the program will crashes or it might just do nothing or just quit, or maybe something else). Look up "C undefined behaviour" on your favorite search engine.


    There is another subtle bug: char x; should be int x; because fgetc returns an int, not a char.

    Read following articles for more information: