我试着用C语言在一个文本文件中的任意位置写东西.
#include <stdio.h>
void write_in_file(FILE *file, char *str, fpos_t *pos){
fsetpos(file, pos);
for(int i=0; str[i] != '\0'; ++i){
fputc(str[i],file);
}
}
int main(){
char *str = "Hola123 Mundo\n";
FILE *file = fopen("database/file_1.txt", "w");
fpos_t pos = 1;
write_in_file(file, str, &pos);
fclose(file);
return 0;
}
文本文件中有以前的信息.我先用pos = 0
写"Hola123 Mundo\n"
,然后用pos = 1
重写.我希望输出文件是
HHola123 Mundo
但是一个GET
'\0'Hola123 Mundo
我知道第一个字节是空字符,因为在十六进制编辑器中,二进制是00
.
我的直觉是,当以"w"
模式打开时,重写整个文件,因此跳过第一个位置会导致跳过00
字节.然后我try 了"w+"
模式,但出现了同样的错误.