This is a follow-up of Conversion of string.endswith method into C, where I'm (trying to) convert a python program into C.
The next part is to properly read data from a file into a buffer and check various places it may error. Here is what I have thus far:
#define BUFFER_SIZE 1024*10
char buffer[BUFFER_SIZE];
void exit_with_error(const char* msg)
{
fprintf(stderr, "%s", msg);
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[])
{
// with open(argv[-1) as f:
// contents = f.read()
// 1. Open file
FILE *fp = fopen(argv[argc-1], "r");
if (fp == NULL) exit_with_error("Error reading file");
// 2. Read and confirm BUFFER is OK
fseek(fp, 0L, SEEK_END);
long fsize = ftell(fp);
if (fsize > BUFFER_SIZE) exit_with_error("File is larger than buffer.");
// 3. Write to buffer and close.
rewind(fp);
size_t read_size = fread(buffer, 1, fsize, fp);
if (read_size != fsize) exit_with_error("There was an error reading the file.");
fclose(fp);
}
I have a few questions on the above:
- For reading a file into a buffer, is it more common to have a standard buffer size and write that into the buffer, or to grab the size and then do a
malloc
. Is there an advantage of one way over the other? - Is it necessary to do all these error-checks in the
main
method, or can I just assume that the user provides the correct file (and it's readable, etc.) - Finally, why do some of the file methods return
size_t
and other returnlong
(such as doingftell
?) Is it safe to usesize_t
for all of them or are there reason why some are not that type?