V
V
Vlad Zaitsev2013-11-04 16:17:24
C++ / C#
Vlad Zaitsev, 2013-11-04 16:17:24

Saving an array to a file and reading it

There is an array: int region_coordinates[10][4];
What is the easiest way to write data from it to a file, and then read it from there and write it back to an array?

Now such a crutch, reading:

    int i_regions=1;
    char filename[11];
    int temp_coordinates[4];
    for (i_regions = 0; i_regions <= 9; i_regions++)
    {
      snprintf(filename,254,"region_%d.bin",i_regions); 
      int settings_file = open(filename, O_RDONLY);
      read(settings_file,temp_coordinates,4*4);
      close(settings_file);
      region_coordinates[i_regions][0]=temp_coordinates[0];
      region_coordinates[i_regions][1]=temp_coordinates[1];
      region_coordinates[i_regions][2]=temp_coordinates[2];
      region_coordinates[i_regions][3]=temp_coordinates[3];
    }


Preservation:

          int temp_coordinates[4];
          int i_regions=1;
          char filename[11];
          for (i_regions = 0; i_regions <= 9; i_regions++)
          {
            snprintf(filename,254,"region_%d.bin",i_regions); 
            int settings_file = open(filename, O_WRONLY | O_CREAT);
            temp_coordinates[0]=region_coordinates[i_regions][0];
            temp_coordinates[1]=region_coordinates[i_regions][1];
            temp_coordinates[2]=region_coordinates[i_regions][2];
            temp_coordinates[3]=region_coordinates[i_regions][3];
            write(settings_file,temp_coordinates,4*4);
            close(settings_file);
          }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xanep, 2013-11-04
@vvzvlad

FILE* fd = fopen("filename", "rb");  //ключ должен быть "rb" - чтение бинарных данных
if (fd == NULL) 
    printf("Error opening file for reading");
size_t result = fread(region_coordinates, 1, sizeof(region_coordinates), fd);
if (result != sizeof(region_coordinates)) 
    printf("Error reading file"); //прочитали количество байт не равное размеру массива
fclose(fd);

FILE* fd = fopen("filename.bin", "wb");
if (fd == NULL) 
    printf("Error opening file for writing");
fwrite(region_coordinates, 1, sizeof(region_coordinates), fd);
fclose(fd);

R
rozhik, 2013-11-04
@rozhik

If the file is binary, then just write
fd = fopen( filename, "wb" ); write( fd, i_regions, sizeof( i_regions ) ); fclose( fd );
, read - instead of wright - read.
If it should be text, editable by hand - then json, inifile or whatever is more convenient to edit (as for me JSON is best).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question