-
Notifications
You must be signed in to change notification settings - Fork 6
/
bintotxt.c
executable file
·64 lines (50 loc) · 1.43 KB
/
bintotxt.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
55
56
57
58
59
60
61
62
63
64
// Given a binary file with one int (n), then n*l floats,
// write ascii file of floats, n per line
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// our own openFile method, which exits gracefully if there's an error
FILE *openFile(char *name, char *mode) {
FILE *f;
if ((f = fopen(name, mode)) == NULL) {
printf("Error opening %s for %s\n", name, mode);
exit(1);
}
return f;
}
int main(int argc, char *argv[]) {
FILE *in, *out;
char inName[128], outName[128];
int numPerLine;
float oneFloat;
int numReadThisLine;
long numRead;
if (argc < 2) {
printf("Usage: %s fileName\n", argv[0]);
printf("Where fileName is name of file to decompress\n");
printf("Decompressed file output in fileName.txt\n");
exit(1);
}
strcpy(inName, argv[1]);
strcpy(outName, inName);
strcat(outName, ".txt");
in = openFile(inName, "r");
out = openFile(outName, "w");
fread(&numPerLine, sizeof(int), 1, in); // read numPerLine from in
// loop: read floats until there are no more to read
numRead = 0;
numReadThisLine = 0;
while (fread(&oneFloat, sizeof(float), 1, in) > 0) { // while there's another float
numRead++;
numReadThisLine++;
fprintf(out, "%f ", oneFloat);
if (numReadThisLine == numPerLine) {
fprintf(out, "\n"); // time for a new line
numReadThisLine = 0;
}
}
printf("Read %ld floats\n", numRead);
fclose(in);
fclose(out);
return 0;
}