[英]How to write pointers inside a binary file? (C)
I am not very used to work with a file, but when is necessary to write strings or normal variables, I don't find any problem to put them inside a binary file. 我不是很习惯使用文件,但是当有必要编写字符串或普通变量时,将它们放在二进制文件中没有任何问题。 However, I have tried several times to save the content of a pointer to pointer (actually, an array of strings) inside a b-file and all the time or my compiler showed an error or just crashed. 但是,我已经尝试过几次将指向指针的指针的内容(实际上是字符串数组)保存在b文件中,并且一直或者我的编译器显示错误或崩溃。 Does someone have an idea of how to make it work? 有人对如何使其工作有想法吗?
A simplified version of the code is down there: 下面是该代码的简化版本:
int main(){
int n;
scanf("%d", &n);
char **campo2 = (char**)malloc(n*sizeof(char*));
campo2[i] = (char*)malloc(20*sizeof(char));
for(int i = 0; i< n; i++){
campo2[i] = foo();
}
FILE *binaryFile = fopen("file.bin", "wb");
if (binaryFile =! NULL){
for(int i = 0;i<n;i++){
fwrite(campo2[i], 20*sizeof(char),1,binaryFile);
}
}
return 0;
}
You probably want something like 您可能想要类似
char * foo(int i)
{
char *s= malloc(20);
fprintf(s,"%018d\r\n",i);
return s;
}
int main()
{
int n;
scanf("%d", &n);
char **campo2 = (char**)malloc(n*sizeof(char*));
for(int i = 0; i< n; i++){
campo2[i] = foo(i);
}
FILE *binaryFile = fopen("file.bin", "wb");
if (binaryFile =! NULL){
for(int i = 0;i<n;i++){
fwrite(campo2[i], 20,1,binaryFile);
}
fclose(binaryFile);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.