I am contacting you because I have a problem with my program. For my studies, I am currently programming in C a function to read a file, I am only allowed to use the following functions/system calls: malloc, free, exit, (f)open, (f)close, (f)read, (f)write, getline, ioctl, usleep, sigaction, signal, stat, lstat, fstat
The problem is that when calling my function my_filetostr(), it blocks the program at the read() system call and nothing happens.
here's my code:
char *my_filetostr(const char *filepath)
{
int fd = 0;
struct stat s;
char *buff = NULL;
if (fd = open(filepath, O_RDONLY) > 0) {
stat(filepath, &s);
buff = malloc(sizeof(char) * s.st_size + 1);
my_printf("fd : %d, size : %d\n", fd, s.st_size);
if (read(fd, buff, s.st_size) == s.st_size) {
buff[s.st_size] = '\0';
}
close(fd);
}
return buff;
}
I specify that my file exists (my error handling works).
I tried to put some my_printf (we had to recode printf) in order to see where the program stops and to display some useful information:
The program is just supposed to move on.
You are assigning to fd inside the if
condition.
This usually causes bugs and should be avoided
Your issue here is specifically because >
has higher precedence compared to =
, so fd
becomes 1 which is stdout.
I have modified your code to highlight the issue https://godbolt.org/z/M4PbcPfev
fd : 1, size : 140728905723182