0

I am a beginner in C language and I'm trying to learn about file handling with functions such as fread() and fwrite(), but there is a problem when I read a string from a file and output it using printf("%s", var); this is the program below to test the functions.

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

void main()
{
    FILE *farquivo;
    int i;
    char text[10];
    char file[51] = "string01  string02  string03  string04  string05  ";

    farquivo = fopen("dados.txt", "w");
    fwrite(file, 1, sizeof(file), farquivo);
    fclose(farquivo);

    farquivo = fopen("dados.txt", "r");
    printf("Sizeof text[] = %d\n", sizeof(text));
    printf("Strings by %%s:\n");
    fread(text, 1, sizeof(text), farquivo);
    printf("%s\n", text);
    fread(text, 1, sizeof(text), farquivo);
    printf("%s\n", text);
    fread(text, 1, sizeof(text), farquivo);
    printf("%s\n", text);
    fread(text, 1, sizeof(text), farquivo);
    printf("%s\n", text);
    fread(text, 1, sizeof(text), farquivo);
    printf("%s\n", text);
    printf("String char by char:\n");
    for(i = 0; i < sizeof(text); i++){
        printf("%c", text[i]);
    }
    printf("\n");
    fclose(farquivo);
}

Everything seems to be okay but the output is odd, this is the output on the console:

Sizeof text[] = 10
Strings by %s:
string01  `FÛu>
string02  `FÛu>
string03  `FÛu>
string04  `FÛu>
string05  `FÛu>
String char by char:
string05

Process returned 0 (0x0)   execution time : 0.051 s
Press any key to continue.

For some reason when i use printf("%s", var); to print the strings the end of it outputs "`FÛu>" but if I print every char of the string one by one this doesn't happen, am I using it in the right way ?

  • 1
    `fread()` doesn't add a 0 byte to the end making `text` not a valid C string. – Shawn Oct 03 '20 at 20:21
  • In C strings are *nul terminated*. Your method of reading a string does not put a nul character at the end of the string, so when you print them out you get garbage after the string. – john Oct 03 '20 at 20:22
  • If you use `fwrite` instead of `printf`, you don't need to have a nul-terminated string. eg, replace `printf`s with `fwrite(text, 1, sizeof text, stdout)`. – William Pursell Oct 03 '20 at 20:28
  • While all strings in C live in char arrays and can be treated as such, a char array does not necessarily hold a string, and if you treat it as a string when it is not, you get undefined behavior. – Chris Dodd Oct 03 '20 at 22:36

1 Answers1

0

When you see weirdness like that it probably means that you are accessing non-allocated memory or uninitialized memory. In your case your string is not null terminated.

When you print a string it will output chars until it reaches the first NULL in memory (i.e. zer0)

shrewmouse
  • 5,338
  • 3
  • 38
  • 43