#include <stdlib.h>
#include <stdio.h>
#include "intarr.h"
/* LAB 6 TASK 1 */
/*
Save the entire array ia into a file called 'filename' in a binary
file format that can be loaded by intarr_load_binary(). Returns
zero on success, or a non-zero error code on failure. Arrays of
length 0 should produce an output file containing an empty array.
*/
int intarr_save_binary( intarr_t* ia, const char* filename ){
if(ia == NULL){
return 1;
}
FILE* WriteFile= fopen(filename, "w");
int length = ia->len;
if(WriteFile == NULL){
return 1;
}
if(fwrite(&length, sizeof(int), 1, WriteFile) != 1){
return 1;
}
if(fwrite(ia->data, sizeof(int), length, WriteFile) != length){
return 1;
}
fclose(WriteFile);
return 0;
}
/*
Load a new array from the file called 'filename', that was
previously saved using intarr_save_binary(). Returns a pointer to a
newly-allocated intarr_t on success, or NULL on failure.
*/
intarr_t* intarr_load_binary( const char* filename ){
int n=0;
int m=0;
unsigned int len = 0;
if(filename == NULL){
return NULL;
}
FILE* ReadFile = fopen(filename, "r");
if(ReadFile == NULL){
return NULL;
}
else{
intarr_t* newInt = intarr_create(len);
while(fread(&m, sizeof(m),1,ReadFile)==1){
newInt->data[n++] = m;
}
return newInt;
}
}
/* LAB 6 TASK 2 */
/*
Save the entire array ia into a file called 'filename' in a JSON
text file array file format that can be loaded by
intarr_load_json(). Returns zero on success, or a non-zero error
code on failure. Arrays of length 0 should produce an output file
containing an empty array.
The JSON output should be human-readable.
Examples:
The following line is a valid JSON array:
[ 100, 200, 300 ]
The following lines are a valid JSON array:
[
100,
200,
300
]
*/
int intarr_save_json( intarr_t* ia, const char* filename ){
if(ia == NULL){
return 1;
}
if(filename == NULL){
return 1;
}
FILE * f=fopen(filename, "w");
fprint(f, "[\n");
for(int m = 0; m< ia->len;m++){
if(m == ia->len-1){
fprintf(f, "%d\n", ia->data[m]);
}
else{
fprintf(f, "%d,\n", ia->data[m]);
}
}
fprintf(f, "]");
fclose(f);
return 0;
}
/*
Load a new array from the file called 'filename', that was
previously saved using intarr_save_json(). The file may contain an array
of length 0. Returns a pointer to a newly-allocated intarr_t on
success (even if that array has length 0), or NULL on failure.
*/
intarr_t* intarr_load_json( const char* filename ){
int number;
if (filename == NULL){
return NULL;
}
FILE* f = fopen(filename, "r");
if(f == NULL){
return NULL;
}
intarr_t* load = intarr_create(0
版权所有:编程辅导网 2021 All Rights Reserved 联系方式:QQ:99515681 微信:codinghelp 电子信箱:99515681@qq.com
免责声明:本站部分内容从网络整理而来,只供参考!如有版权问题可联系本站删除。