abC primeri - datoteke/cplxReadWrite.c

cplxReadWrite.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>

struct cplx {
  float re;
  float im;
};

struct cplx stevila[5] = 
  {{1,2},{-1,3},{2,-2},{0,1},{-1,0}};

struct cplx prebranaStevila[5];

void zapisi(void) {
  FILE *d;

  // datoteko odpremo za pisanje (binarno)
  if ((d = fopen("c:\\rand.txt", "wb")) == NULL)
    exit(1);

  int i;
  for (i=0; i<5; i++) {
  	fwrite(&(stevila[i]),sizeof(struct cplx), 1, d);
  }

  fclose(d);
}

void preberi(void) {
  FILE *d;
  
  // datoteko odpremo za branje (binarno)
  if ((d = fopen("c:\\rand.txt", "rb")) == NULL)
    exit(1);

  int i=0;
  // beremo, dokler so stevila v datoteki in 
  // dokler imamo v tabeli se prostor
  while ((i<5) && (!feof(d))) 
    fread(&(prebranaStevila[i++]), 
          sizeof(struct cplx), 1, d);

  fclose(d);
}

main() {
  zapisi(); 
  preberi();

  int i;
  for (i=0; i<5; i++)
	printf("%.2f + %.2f i\n",
      prebranaStevila[i].re, prebranaStevila[i].im);
}

    Nazaj...