3 ms·
Honestly? This seems more complex than necessary. In C, in a handful of minutes (and with no reference): #include <stdio.h> int read_and_sum_ints(const ch
by fao_ 10y ago
Honestly? This seems more complex than necessary.
In C, in a handful of minutes (and with no reference):
#include <stdio.h>
int read_and_sum_ints(const char *filename, int n)
{
FILE *fd = fopen(filename, "r");
int c = getc(fd);
int sum = 0;
while (n-- > 0 && c) {
int m = 0;
while (c && c != '\n' && c != '\r')
m = (m*10 + (c - '0'));
sum += m;
}
fclose(fd);
return sum;
}
int main(int argc, char **argv)
{
print("%d\n", read_and_sum_ints("foo", 10));
return 0;
}
Given that I'm currently just an intern, I would expect both junior and senior developers to be able to do this.
- vonmoltke 10y agoI wouldn't be able to do that off the top of my head because, in my C experience, I hardly ever read files. Everything we did was reading from or writing to memory buffers. Furthermore, we did almost all system interactions through a platform-independent middleware interface. So, while I, for example, knew what a semaphore was and how to use it I could not remember the standard Linux interface for semaphores because we used the platform-independent API for ours. Expecting people to remember APIs off the top of their heads is ridiculous. Some do, some don't. The people who don't aren't lesser engineers just because they don't.
- fao_ 10y agoI agree people shouldn't have to remember APIs, but you should at least have a vague idea of roughly how to go about reading a file and parsing numbers from it.
- dghf 10y agoIf the first character in file "foo" isn't a null, a newline or a carriage return, your program will enter an infinite loop at line 9 :)
- fao_ 10y agoYes. EOF is 0, so it will grab all the characters as digits, for the length of the file up until an EOF.
- dghf 10y agoThe value of EOF is platform-specific, but is commonly -1. I'm fairly sure it's never 0. But I was referring more to the fact that c is set exactly once in line 4 (`int c = getc(fd)`), outside of the nested loops, and never touched again. So if it's not initially a NULL, newline or CR, it never will be, and the inner loop will never exit.
- Crespyl 10y agoAs long as we're posting code/golfing (and since I've been lots of file parsing lately and it's fresh): use std::io::prelude::*; use std::fs::File; fn main() { let mut s = String::new(); File::open("numbers.txt") .unwrap() .read_to_string(&mut s); let sum = s.lines() .map(|l| l.parse::<i32>().unwrap()) .fold(0, |acc, i| acc+i); println!("{}", sum); }