home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Usenet 1994 October
/
usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso
/
misc
/
volume26
/
pico
/
part01
/
file.c
< prev
next >
Wrap
C/C++ Source or Header
|
1991-12-14
|
2KB
|
86 lines
#include <string.h>
#include <ctype.h>
#include "pico.h"
int nfiles = 2;
Buf buf[NFILES];
extern int findfile(char *name) {
int i;
if (strcmp(name, "old") == 0)
return 1;
for (i = 2; i < nfiles; i++)
if (strcmp(buf[i].name, name) == 0)
return i;
return -1;
}
extern void showfiles() {
int i;
if (nfiles == 2) {
fprintf(stderr, "no files open\n");
} else {
for (i = 2; i < nfiles; i++)
printf("$%d = %s\n", i - 1, buf[i].name);
}
}
extern void writefile(char *name) {
int f = findfile(name);
FILE *fp = fopen(name, "w");
if (fp == NULL) {
perror(name);
return;
}
fprintf(fp, "P5 %d %d 255\n", DEF_X, DEF_Y);
fwrite(buf[0].data, 1, DEF_X * DEF_Y, fp);
fclose(fp);
if (f < 0) {
if (nfiles >= NFILES)
return;
f = nfiles++;
buf[f].name = strdup(name);
buf[f].data = ealloc(DEF_X * DEF_Y);
}
memcpy(buf[f].data, buf[0].data, DEF_X * DEF_Y);
}
#define failif(x,y) if (x) {y; f = -1; goto fail;}
#define next fgetc(fp)
extern int readfile(char *name) {
FILE *fp = fopen(name, "r");
int c,i,f = findfile(name);
failif(f > 0 && nfiles >= NFILES, fprintf(stderr, "too many open files\n"))
failif(fp == NULL, perror(name))
failif(next != 'P' || next != '5', fprintf(stderr, "%s: bad magic number\n", name))
while (isspace(c = next))
;
failif(!isdigit(c), fprintf(stderr, "%s: expected a decimal number, saw: %c\n", name, c))
for (i = c - '0'; isdigit(c = next); i = i*10 + c-'0')
;
failif(i != DEF_X, fprintf(stderr, "%s: expected an x-coordinate of %d\n", name, DEF_X))
while (isspace(c))
c = next;
for (i = c - '0'; isdigit(c = next); i = i*10 + c-'0')
;
failif(i != DEF_Y, fprintf(stderr, "%s: expected a y-coordinate of %d\n", name, DEF_Y))
while (isspace(c))
c = next;
for (i = c - '0'; isdigit(c = next); i = i*10 + c-'0')
;
failif(i != 255, fprintf(stderr, "%s: expected a grey scale of 255, saw\n", name, i))
if (!isspace(c))
ungetc(c,fp);
if (f < 0) {
f = nfiles++;
buf[f].name = strdup(name);
buf[f].data = ealloc(DEF_X * DEF_Y);
}
fread(buf[f].data, 1, DEF_X * DEF_Y, fp);
fail:
fclose(fp);
return f;
}