Discussione: [C] ..e le stringhe?!?
View Single Post
Old 19-10-2005, 17:27   #5
ilsensine
Senior Member
 
L'Avatar di ilsensine
 
Iscritto dal: Apr 2000
Città: Roma
Messaggi: 15625
Il metodo classico è allocare un buffer grande quanto l'intero file, e leggerlo dentro. E' un metodo triviale ma poco efficiente, soprattutto se il file è grande e hai poca memoria. Meglio mappare il file nello spazio di indirizzi del processo.

Ad esempio questo programma mappa un file, e lo stampa un carattere alla volta (è per linux/unix, ma ti rende l'idea):

Codice:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
	int fd;
	struct stat st;
	char *map;
	int x;

	if (argc<2) {
		printf("%s <file>\n", argv[0]);
		return -1;
	}

	fd = open(argv[1], O_RDONLY);
	if (fd<0) {
		perror("open");
		return -1;
	}

	fstat(fd, &st);

	map = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
	if (map==MAP_FAILED) {
		perror("mmap");
		return -1;
	}
	close(fd);

	for (x=0; x<st.st_size; ++x)
		printf("%c", map[x]);

	munmap(map, st.st_size);
	return 0;
}
__________________
0: or %edi, %ecx; adc %eax, (%edx); popf; je 0b-22; pop %ebx; fadds 0x56(%ecx); lds 0x56(%ebx), %esp; mov %al, %al
andeqs pc, r1, #147456; blpl 0xff8dd280; ldrgtb r4, [r6, #-472]; addgt r5, r8, r3, ror #12
ilsensine è offline   Rispondi citando il messaggio o parte di esso