-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadfile.c
44 lines (34 loc) · 948 Bytes
/
readfile.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
// Copyright (c) 2015, Sam Silberstein. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License").
// Author: [email protected]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "sim.h"
unsigned short gethalf(void *p) { return *(unsigned short *)p; }
unsigned int getfull(void *p) { return *(unsigned int *)p; }
char *readfile(char *filename)
{
struct stat fileinfo;
if (stat(filename, &fileinfo) < 0) {
perror("Cannot open file"); exit(1);
}
int filesize = (int)fileinfo.st_size;
#ifdef READELF_DEBUG
printf("File size is: %d\n", filesize);
#endif
FILE *fd = fopen(filename, "r");
if (!fd) {
perror("Cannot open file"); exit(1);
}
char* buf = malloc(filesize);
if (!buf) {
perror("malloc failed"); exit(1);
}
if (fread(buf, 1, filesize, fd) <= 0) {
perror("Cannot read file"); exit(1);
}
fclose(fd);
return buf;
}