質問

I'm trying to make a simple program for inserting some text on specific position in existing text file. For example if is in file text.txt text "sample text", after running program should be in text.txt "saminserting textple text". But sometimes program inserts some Weird symbols to the end of text, so in this case I got "saminserting textple textX€" (where is for some reason "X€" on the end of text) and I can't figure out, why. My code:

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


int main ( int argc, char *argv[] )
{

FILE *file;

 file = fopen("text.txt", "rb+"); //processed file
 if (file == NULL) return 0;

 char *test = "inserting text"; //text for inserting
 char *buffer;
 int size;

 fseek(file, 0L, SEEK_END);
 size = ftell(file);

 fseek(file, 3L, SEEK_SET);
 buffer = malloc(abs(3L - size) + 1);
 fread(buffer, abs(3L - size), 1, file);

 fseek(file, 3L, SEEK_SET);
 fwrite(test, strlen(test), 1, file);
 fwrite(buffer, strlen(buffer), 1, file);

 free(buffer);
 fclose(file);

 return 0;
}

I'll be grateful for any help.

役に立ちましたか?

解決

buffer = malloc(abs(3L - size) + 1);
fread(buffer, abs(3L - size), 1, file);
...
fwrite(buffer, strlen(buffer), 1, file);

You never null-terminate buffer so you potentially write a different about to what you read. Do this instead. (But really, use size-3 or something nicer...)

fwrite(buffer, abs(3L - size), 1, file);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top