-1

I'm a C learner and I'm having big difficulties with Files in C. Everytime I try to make a small program in C with Files, like printing a few datas on a simple txt it would ALWAYS print junk characters and/or ignore some of said datas. Even if I entirely copy a piece of presumably functioning code from stackoverflow.com or from Deitel textbook it just never works. Here's an example of code that I have been trying:

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

// a struct to read and write
struct person 
{
int id;
char fname[20];
char lname[20];
};

int main ()
{
FILE *outfile;
  
// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
    fprintf(stderr, "\nError opend file\n");
    exit (1);
}

struct person input1 = {1, "rohan", "sharma"};
struct person input2 = {2, "mahendra", "dhoni"};
  
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
  
if(fwrite != 0) 
    printf("contents to file written successfully !\n");
else 
    printf("error writing file !\n");

// close file
fclose (outfile);

return 0;
}

This is a simple code that should write a few things on a dat. file. In this case, it won't print the numbers, just a small rectangle, and it prints the names without a newline. But I have seen worst, as many other codes will just print many junk characters. I'm using codeBlocks. Also, I have noticed that everything seems to work until I only use fprintf, fscanf and simple variables instead of structs. Anything else makes the code do weird stuff. Please help :(

klutt
  • 30,332
  • 17
  • 55
  • 95
Tiziano666
  • 21
  • 5
  • `if(fwrite != 0) ` doesn't do what you think it does. Please take a few steps back, and pick up a beginners C book to read about files and how to use [the `fwrite` function](https://en.cppreference.com/w/c/io/fwrite). – Some programmer dude Jul 04 '21 at 18:18
  • 1
    The number are store binary, so a text editor will not show them. If you read the file using your structs, it should work. – Mario The Spoon Jul 04 '21 at 18:18
  • The output of your program is just fine when viewed as a byte dump, but not with a text editor. The problem seems to be with your idea of what the result should be, and the distinction between formatted binary files, and text files. – Weather Vane Jul 04 '21 at 18:24
  • You are writing a binary file not a text file. It is probably doing exactly as you ask. It is no "junk" you are just trying to read it as text which it is not. Use a hex viewer/editor to inspect the content. Or just round-trip it read it back into the structures and verify it is correct (in the debugger for example). If you want the output in human readable form use `fprintf()` instead. – Clifford Jul 04 '21 at 18:31
  • @MarioTheSpoon but it's a dat file, isn't it supposed to to display any kind of data? Should I open it with something other than the text editor? – Tiziano666 Jul 04 '21 at 18:33
  • 1
    The name of the file makes no difference. It only hints as to the content of the file. The reason the "names have no newline" is because there was none in the `struct` data and none that you explicitly wrote to the file. And after `int num = 42;` this `fwrite(&num, sizeof num, 1, outfile);` and this `fprintf(outfile, "%d", num);` do quite different things. – Weather Vane Jul 04 '21 at 18:34
  • @WeatherVane all right but I have tried codes written in the deitel textbook (copying them without making the smallest change) and it still doesn't work, I don't understand what I am supposed to do. – Tiziano666 Jul 04 '21 at 18:42
  • 2
    Please explain in the question what you mean by "doesn't work". Looking at the file content written by `fwrite(&num, sizeof num, 1, outfile);` with a text editor isn't going to show you anything useful, because the data output *isn't text*. It won't matter whether the output file is named "test.txt" or "test.dat" – Weather Vane Jul 04 '21 at 18:44
  • @WeatherVane Forgive my ignorance, I thought that the txt file was supposed to display exactly what i wanted (numbers and words) because when I only used fprintf and fscanf it worked, I opened the txt file after compiling the code and the results were crystal clear. Also, my book doesn't mention anything about txt files not working properly with fwrite and other functions. Am I supposed to convert the txt files in something else or what? – Tiziano666 Jul 04 '21 at 18:49
  • It is the instructions that you use to write to the file that matter, not what the typically understood format of certain filename suffixes is. I have been trying to find some previous questions by googling "c stackoverflow difference between binary and text file". There are several to be found, such as [this question](https://stackoverflow.com/questions/6039050/difference-between-text-file-and-binary-file). Perhaps you could spend some time browsing around to gain more knowledge of the matter, and the topic is probably covered well in textbooks too. – Weather Vane Jul 04 '21 at 18:50
  • ... as to what you do with file, it was suggested above that the binary file is suitable for reading back into a program designed for that purpose: the complement of the program you copied. – Weather Vane Jul 04 '21 at 18:56
  • You might want to read [these course notes](https://www.eskimo.com/~scs/cclass/int/sx3.html). The code you've shown writes a "binary data file". If you expected to be able to see your data (and not those "junk characters"), you may have wanted a "text data file". Those course notes explain the difference. – Steve Summit Jul 04 '21 at 19:27

1 Answers1

0

As pointed out by others in the comments, fwrite will output in binary, not text. If you need to output in text, you should perhaps create a print_person function, something like this:

int print_person(struct person *p, FILE *fp) {
    return fprintf(fp,"%d\n%s\n%s\n",p->id,p->fname,p->lname);
}

And then in your main, call it like this:

if (print_person(&input1,outfile) < 0) {
    printf("Error writing to file\n");
    exit(-1);
}
SGeorgiades
  • 1,771
  • 1
  • 11
  • 11