Question

my problem looks like this: I make a char array, lets say its length is A, then i write this array to file, then read it from the same file and its length is not A anymore, its bigger.. Source code:

char encrypted1[] = "abcdefghijklmnopqrstuvqwxyz";
int encrypted1_len;
char *encrypted;
int encrypted_len;
encrypted1_len = strlen((char*)encrypted1);

f_cypher = fopen(CYPHER_FILE, "w");
fprintf(f_cypher, "%s", encrypted1);
fclose(f_cypher);

stat(CYPHER_FILE, &st);
size = st.st_size;
encrypted = malloc(size * sizeof *encrypted);
f_cypher = fopen(CYPHER_FILE, "r");
len = fread(encrypted, 1, size, f_cypher);
encrypted1[len] = '\0';
fclose(f_cypher);

encrypted_len = strlen((char*) encrypted);
printf("%s", encrypted);

In this example the lengths are 27 and then 40.

Était-ce utile?

La solution

You're not allocating enough space for the string you read back. Your encrypted1 has 26 characters and one \0 string end marker, which makes 27. Now you write those 26 bytes to the file (do a ls -l - check the 26), allocate 26 bytes, and set encrypted1[len] to '\0', which is memory that you haven't allocated. Anything weird can happen from now on. Change size in malloc to (size+1) and look what happens.

Autres conseils

The problem is that C strings are supposed to be null terminated, but you're not writing the null character at the end.

One solution is to add the null character when you write it to the file (which makes it unnecessary to write the size explicitly):

encrypted1_len = strlen(encrypted1) + 1;

Or you can add the null character when you read it back from the file:

encrypted = malloc(size * sizeof *encrypted + 1);
encrypted[size] = '\0';

Try this my friend:

char encrypted[] = "abcdefghijklmnopqrstuvqwxyz"; /*27 characters */
f_cypher = fopen(CYPHER_FILE, "w");
fprintf(f_cypher, "%s", encrypted); /* could use fputs() instead */
fclose(f_cypher);

int source_length = sizeof(encrypted); /* could use strlen(encrypted) instead */
char buffer[source_length+1];  /* extra character for null terminator */
f_cypher = fopen(CYPHER_FILE, "r");
int len = fread(buffer, 1, source_length, f_cypher);
buffer[len] = '\0';
printf("%s\n",buffer);

printf("encrypted is %u characters long.\n", strlen(encrypted));
printf("buffer is %u characters long.\n", strlen(buffer));

Using encrypted and encrypted1 for writing and reading is bound to cause confusions so I've changed destination variable to buffer.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top