tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
28
Task/Read-entire-file/C/read-entire-file-1.c
Normal file
28
Task/Read-entire-file/C/read-entire-file-1.c
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
char *buffer;
|
||||
FILE *fh = fopen("readentirefile.c", "rb");
|
||||
if ( fh != NULL )
|
||||
{
|
||||
fseek(fh, 0L, SEEK_END);
|
||||
long s = ftell(fh);
|
||||
rewind(fh);
|
||||
buffer = malloc(s);
|
||||
if ( buffer != NULL )
|
||||
{
|
||||
fread(buffer, s, 1, fh);
|
||||
// we can now close the file
|
||||
fclose(fh); fh = NULL;
|
||||
|
||||
// do something, e.g.
|
||||
fwrite(buffer, s, 1, stdout);
|
||||
|
||||
free(buffer);
|
||||
}
|
||||
if (fh != NULL) fclose(fh);
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
29
Task/Read-entire-file/C/read-entire-file-2.c
Normal file
29
Task/Read-entire-file/C/read-entire-file-2.c
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
|
||||
int main()
|
||||
{
|
||||
char *buffer;
|
||||
struct stat s;
|
||||
|
||||
int fd = open("readentirefile_mm.c", O_RDONLY);
|
||||
if (fd < 0 ) return EXIT_FAILURE;
|
||||
fstat(fd, &s);
|
||||
/* PROT_READ disallows writing to buffer: will segv */
|
||||
buffer = mmap(0, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
|
||||
|
||||
if ( buffer != (void*)-1 )
|
||||
{
|
||||
/* do something */
|
||||
fwrite(buffer, s.st_size, 1, stdout);
|
||||
munmap(buffer, s.st_size);
|
||||
}
|
||||
|
||||
close(fd);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue