Forum: Mikrocontroller und Digitale Elektronik von C++ nach C


von Dan (Gast)


Lesenswert?

kann mir jemand bitte das in C übersetzen?? bin nicht so gut in C
vielen dank im voraus

void FileAR(string filename,bool x)
{
  fstream file(filename.c_str(),ios::in | ios::out | ios::binary);

  if(!file)
    {
      cout <<"Could not open file";
      return;
    }

  unsigned size;

  file.seekg(0,ios::end);
  size=file.tellg();
  file.seekg(ios::beg);

  file.clear();

  unsigned pos;

  int n_blocks=size/BLOCK_SIZE;
  if(size%BLOCK_SIZE!=0)
      ++n_blocks;

  for(int i=0;i<n_blocks;i++)
    {
      unsigned char data[BLOCK_SIZE];
      pos=file.tellg();

      file.read((char*)data,BLOCK_SIZE); // read data block

     ---

      file.seekp(pos);
      file.write((char*)data,BLOCK_SIZE);

      memset(data,0,BLOCK_SIZE);
    }
  file.close();
}

von Georg B. (diereinegier)


Lesenswert?

Mit den folgenden Funktionen der Standardbibliothek bekommst Du das hin.
fopen
fstat/stat/lstat, um die Größe herauszubekommen-
fseek
fread
fwrite
fclose

Im Grunde ist der fstream ein dünner Wrapper um
1
FILE*
.

Schaffst Du schon!

von Daniel A. (daniel-a)


Lesenswert?

Ungetestet, C99:
1
#include <stdio.h>
2
#include <stdbool.h>
3
4
#define FOPEN_READ   "r"
5
#define FOPEN_WRITE  "w"
6
#define FOPEN_BINARY "b"
7
8
void FileAR( const char* filename, bool x ){
9
  FILE* file = fopen(filename, FOPEN_READ FOPEN_WRITE FOPEN_BINARY );
10
11
  if(!file){
12
    printf("Could not open file");
13
    return;
14
  }
15
16
  fseek( file, 0, SEEK_END );
17
  size_t size = ftell( file );
18
  fseek( file, 0, SEEK_SET );
19
20
  size_t n_blocks = ( size + BLOCK_SIZE - 1 ) / BLOCK_SIZE;
21
22
  for( size_t i=0; i<n_blocks; i++ ){
23
    unsigned char data[BLOCK_SIZE] = {0};
24
    size_t pos = ftell( file );
25
26
    fread( data, 1, BLOCK_SIZE, file ); // read data block
27
28
     ---
29
30
    fseek( file, pos, SEEK_SET );
31
    fwrite( data, 1, BLOCK_SIZE, size );
32
  }
33
34
  fclose( file );
35
}

von Dan (Gast)


Lesenswert?

vielen dank

aber kann mir jemand das erklären ;


  fseek( file, 0, SEEK_END );
  size_t size = ftell( file );
  fseek( file, 0, SEEK_SET );

und
fseek( file, pos, SEEK_SET );

von Christian (Gast)


Lesenswert?


Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
Bestehender Account
Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Noch kein Account? Hier anmelden.