Home > Back-end >  After writing to a text file using c there are only some unreadable characters in that file
After writing to a text file using c there are only some unreadable characters in that file

Time:10-10

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.stack.imgur.com/uqOxs.jpg

CodePudding user response:

This is an interesting question and the answer takes some thought and experimentation for a beginner to grasp. Your program actually does write the numbers 1 through 10 into my.txt, but in binary form. To prove this, try compiling and running the following, second program, which reads from the file the numbers your first program has written to the file.

#include <iostream>
#include <cstdio>
using namespace std;

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

    for (int i =1; i<= 10; i  ){
        const int m = getw(fp);
        cout << m << " ";
    }
    cout << "\n";

    fclose(fp);

    return 0;
}

To be readable in text form, the numbers would want to have been written to the file in ASCII (a subset of UTF-8-encoded Unicode). However, binary may be a reasonable or even a superior way to represent data like yours, depending on the application.

Because future readers may study this answer I should point out that the answer's code's style mimics your code's style to make the answer easier for you to understand. Otherwise, the code would be written in a more standard, more modern C style and would look rather different. To model future code on this answer therefore is not recommended.

CodePudding user response:

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;
        }
    }
}
  • Related