0

I want to store some strings in a text file (one string per line), but on compilation, some unnecessary zeroes get added at the end of each string in the text file. Following is my code :- **

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

    int main()
    {
        int i=0;
        char *name[4]={"ABC","agb","thi","yuun"};
        FILE *pp;
        pp=fopen("random_name.txt","w");
        for(int i=0;i<4;i++)
        {
            fwrite(name[i],strlen(name[i])+1,1,pp);
            fputs("\n",pp);
        }
        fclose(pp);
        return 0;
    }

** Here's the text file

Nova Stark
  • 55
  • 7

2 Answers2

0

Just remove the +1 from strlen(name[i])+1 and update your fwrite() function:

fwrite(name[i],strlen(name[i]),1,pp);

Shubham
  • 1,153
  • 8
  • 20
0

unnecessary zeroes get added at the end of each string in the text file.

Reason: Each of name[i] string ends with \0 (ASCII 0). You are giving, strlen(name[i])+1 as the argument to fwrite. So, the null terminating character (\0) will also be written to the file.

Solution : To avoid it, change fwrite(name[i],strlen(name[i])+1,1,pp); to fwrite(name[i],strlen(name[i]),1,pp);

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26