0
我正在試圖製作一個簡單的程序,用於在現有文本文件的特定位置插入一些文本。例如,如果在文件text.txt文本「示例文本」中,運行程序之後應該在text.txt「saminserting textple text」中。但有時程序會在文本的末尾插入一些怪異的符號,所以在這種情況下,我得到了「插入文本textX€」(出於某種原因,文本結尾處的「X€」),我無法弄清楚,爲什麼。 我的代碼:將文本插入文件時結束時出現奇怪的符號
#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;
}
我會感謝任何幫助。
爲什麼'大小-3'而不是'abs(3L-size)'? – Roddy
緩衝區是否終止? – BLUEPIXY
@BLUEPIXY,好吧,只有當文件包含空終止的字符串。這是最不可能的。 – Roddy