Search code examples
c++pointersfile-handling

After writing to a text file using c++ there are only some unreadable characters in that file


I wrote a program to write some integers to a text file using c++. But after running the code, there are only some unreadable characters inside the text file.

How do I fix it?

My code is as follows.

#include <iostream>
using namespace std;

int main(){
    FILE *fp;
    fp=fopen("my.txt","w");

    for (int i =1; i<= 10; i++){
      putw(i, fp);
    }

    fclose(fp);

    return 0;
}

This is how it shows the text file after running the code above. [1]: https://i.sstatic.net/uqOxs.jpg


Solution

  • after running the code, there are only some unreadable characters inside the text file. How do I fix it? ... This is how it shows the text file after running the code

    The problem is that you expect it to be a text file, but putw writes the ints to the file in binary format.

    In order to get readable characters in a text file, use the std::fprintf function instead of putw.

    #include <cstdio>  // This is correct header for `fopen`
    
    int main(){
        std::FILE* fp = std::fopen("my.txt", "w");
        if (fp) {
            for (int i =1; i<= 10; i++){
                std::fprintf(fp, "%d", i);
            }
            std::fclose(fp);
        }
    }
    

    The C++ way to do the same thing would be to use fstreams:

    #include <fstream>
    
    int main() {
        std::ofstream fs("my.txt");
        if (fs) {
            for (int i = 1; i <= 10; i++) {
                fs << i;
            }
        }
    }