Phát Nguyễn
Phát Nguyễn

Reputation: 17

Error with binary file

#include<stdio.h>
#include <string.h>
void main()
{
    FILE *f = fopen("F:\\hongphat.txt","wb+");
    char *password = "password";
    int l = strlen(password);
    fwrite(&l, sizeof(int), 1, f);
    fwrite(&password, 1, strlen(password), f);
    fclose(f);

    FILE *g = fopen("f:\\hongphat.txt", "rb+");
    char *passwordsame = new char[250];
    int length;
    fread(&length, sizeof(int), 1, g);
    fread(passwordsame, length, 1, g);
    int k = strlen(passwordsame);
    fclose(g);
    delete[]passwordsame;
}

i code this example to make a password for a file, but when i did that, i see that k is not equal to length ( length = 8), can anyone show my mistake

Upvotes: 2

Views: 52

Answers (2)

Subinoy
Subinoy

Reputation: 488

There is so many syntax error in this C code. In this code as you have used

*password

for that you don't need to use '&' in the fwrite, but if you want to use '&' then you have to declare it

char password[]="password";

I modified your code a little. The code should be

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

void main()
{
    FILE *f, *g;
    int l,k,length,n;
    char passwordsame[255];
    char password[]="password";
    f = fopen("hongphat.txt","wb+");
    l= strlen(password);
    fwrite(&l, sizeof(int), 1,f);
    fwrite(&password,strlen(password)+1,1, f);
    fclose(f);

    g = fopen("hongphat.txt", "rb+");
    fread(&length, sizeof(int), 1, g);
    printf("%d\n\n",length);
    fread(&passwordsame, length, 1, g);
    passwordsame[length]='\0';
    k = strlen(passwordsame);
    fclose(g);
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

When you write the password

fwrite(&password, 1, strlen(password), f);

The expression &password does not give you the password-string, it gives you the address of where the password variable is located. So what you are writing is the pointer to the string and not the string itself.

To solve it, just change to

fwrite(password, 1, strlen(password), f);

In other words, remove the address-of operator &.


You also have another mistake, in that when you read the password from the file, you don't terminate the string. All strings needs to be terminated by the character '\0'.

After you have read the length and the password, do e.g.

passwordsame[length] = '\0';

Upvotes: 2

Related Questions