简体   繁体   中英

Reading Text File error C

When generating 4 character hashes and writing it to a text file I run into an error where if I try and print the hashes to the console it only prints the first line of the text file. Weirdly enough it prints the whole text file to the console if I get rid of the generateHashTable(); line and edit the text file by adding a space or something. I don't understand why it does this.

Your main problem is this:

fwrite("\n", sizeof("\n"), 1, fptr);

fwrite() will write two characters here, a '\\n' and an '\\0' , which, while not incorrect, is clearly not what you want. What this will cause is every single line in your file after the first to begin with a null character. When you try then to printf() those lines, it'll stop at that null character because that's where it thinks the end of the string is, the end result being nothing will be printed. This is why it's only printing out your first line. You should replace this line with:

fputc('\n', fptr);

A couple other obvious errors:

char *c=malloc(sizeof 5);

is almost certainly not what you want. This will allocate a number of bytes equal to sizeof(int) . What you need is:

char * c = malloc(5);

If you're on a system with 32 bit int s, the following line:

c[4] = '\0';

gives you undefined behavior immediately, since you're trying to write to the fifth byte of a four byte allocation of memory.

Then this:

if (fptr == NULL)

why are you checking if fopen() returned successfully after you've done all your reading and writing to the file? You should be checking it before you do that.

Since you don't show your definitions for things like E() , fptr , chunkout , and the like, it's quite possible there are other glaring errors that cannot be determined in the absence of those definitions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM