Dateien

Dateien

Dateiattribute

Beispiel:

manfred% ls -l . 
… 
drwxr-xr-x 10 manfred user 2048 2021-08-21 12:41 progintro 
-rw-r--r-- 1 manfred user 1047 2021-09-16 15:56 hello.c
… 

Operationen auf Dateien

Verzeichnisse

Unix Pfadnamen

Formatierte Eingabe: fscanf

Öffnen von Dateien: fopen

Lesen von Datei – Ausgabe auf stdout

// Konvention: „fp“ kurz für „file_pointer“ 
FILE *fp = fopen(“datei.txt“, “r“); 
int a, b; 
if (fp == NULL ) { 
	perror(“Fehler beim öffnen der Datei“); 
	return 1; } 
while (fscanf(fp, “%d %d\n“, &a, &b) != EOF) { 
	printf(“%d %d\n“, a, b); } 
fclose(fp);

Lesen von Datei – Ausgabe von Datei

FILE *fpin = fopen(“datei_in“, „r“); 
FILE *fpout = fopen(“datei_out“, „a“); 
int a, b;
while (fscanf(fpin, “%d %d\n“, &a, &b) != EOF) { 
	fprintf(fpout, “%d + %d = %d\n“, a,b,a+b); 
} 
fclose(fpin); fclose(fpout);

Formatierte Eingabe: fgets & sscanf

char buf[200]; 
int a, b; 
char *h = fgets(buf, 200, stdin); // Liest bis zu 199 Zeichen + '\0'
if (h==NULL) { 
	printf(„error in fgets“); 
	exit(1); 
} 
int ret = sscanf(buf, „%d %d“, &a, &b); 
if (ret == 2) { 
	printf(„read 2 integers: %d %d\n“, a, b); 
} else { 
	fprintf(stderr, „error reading 2 integers\n“); 
}