Explorar el Código

Fix file reading and move it into a function

There were a few problems with the previous implementation:

- the `fread` call was wrong, reading too much data
- the buffer was not `memset` prior to reading
Lucas Stadler %!s(int64=9) %!d(string=hace) años
padre
commit
be1d5b4aa0
Se han modificado 1 ficheros con 41 adiciones y 18 borrados
  1. 41 18
      c/jsc-test.c

+ 41 - 18
c/jsc-test.c

@ -11,6 +11,8 @@ char console_log_buf[CONSOLE_LOG_BUF_SIZE];
11 11
JSStringRef to_string(JSContextRef ctx, JSValueRef val);
12 12
JSValueRef evaluate_script(JSContextRef ctx, char *script, char *source);
13 13
14
char* get_contents(char *path);
15
14 16
JSValueRef function_console_log(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) {
15 17
	for (int i = 0; i < argumentCount; i++) {
16 18
		if (i > 0) {
@ -49,27 +51,14 @@ JSValueRef function_import_script(JSContextRef ctx, JSObjectRef function, JSObje
49 51
		JSStringGetUTF8CString(path_str_ref, path, 100);
50 52
		JSStringRelease(path_str_ref);
51 53
52
		FILE *f = fopen(path, "r");
53
		if (f == NULL) {
54
			perror("fopen");
55
			goto err;
56
		}
57
58
		struct stat f_stat;
59
		if (fstat(fileno(f), &f_stat) < 0) {
60
			perror("fstat");
61
			goto err;
62
		}
63
64
		char *buf = malloc(f_stat.st_size * sizeof(char));
65
		fread(buf, sizeof(char), f_stat.st_size, f);
66
		if (ferror(f)) {
67
			perror("fread");
68
			free(buf);
54
		char full_path[150];
55
		snprintf(full_path, 150, "%s/%s", "out", path);
56
		char *buf = get_contents(full_path);
57
		if (buf == NULL) {
69 58
			goto err;
70 59
		}
71 60
72
		evaluate_script(ctx, buf, path);
61
		evaluate_script(ctx, buf, full_path);
73 62
		free(buf);
74 63
	}
75 64
@ -164,3 +153,37 @@ JSValueRef evaluate_script(JSContextRef ctx, char *script, char *source) {
164 153
165 154
	return val;
166 155
}
156
157
char *get_contents(char *path) {
158
	FILE *f = fopen(path, "r");
159
	if (f == NULL) {
160
		perror("fopen");
161
		goto err;
162
	}
163
164
	struct stat f_stat;
165
	if (fstat(fileno(f), &f_stat) < 0) {
166
		perror("fstat");
167
		goto err;
168
	}
169
170
	char *buf = malloc(f_stat.st_size);
171
	memset(buf, 0, f_stat.st_size);
172
	fread(buf, f_stat.st_size, 1, f);
173
	buf[f_stat.st_size] = '\0';
174
	if (ferror(f)) {
175
		perror("fread");
176
		free(buf);
177
		goto err;
178
	}
179
180
	if (fclose(f) < 0) {
181
		perror("fclose");
182
		goto err;
183
	}
184
185
	return buf;
186
187
err:
188
	return NULL;
189
}