Open file snippets
Open file snippets
C character by character
#include "stdio.h"
#include "stdlib.h"
#define FILENAME "input.txt"
int main() {
FILE *fp = fopen(FILENAME, "r");
if(fp == NULL) {
printf("something went wrong with reading the file\n");
return EXIT_FAILURE;
}
char ch;
while((ch = fgetc(fp) != EOF)) {
}
return EXIT_SUCCESS;
}
C++
std::cin reads input until the first whitespace character is countered.
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::cout << input << "\n";
while(std::cin >> input) {
std::cout << input << "\n";
}
return 0;
}
get line from input
#include <iostream>
#include <string>
int main() {
std::string input;
while(std::getline(std::cin, line)) {
std::cout << line << "\n";
}
return 0;
}
Erlang
-module(example).
-export([main/0]).
process_char(Cur) ->
io:format("do something with ~c", [Cur]).
main() ->
case file:read_file("input.txt") of
{ok, BinaryData} ->
Ch = binary_to_list(BinaryData),
process_char(Ch);
{error, _} ->
io:format("something went wrong with the file")
end.
erlc example.erl
erl -noshell -s example main -s init stop < input.txt
Using escript
rebar3 escriptize && ./_build/default/bin/main < input.txt
-module(main).
-export([main/1]).
main(_Args) ->
Line = io:get_line(""),
io:format("~s", [Line]).
improvements to reading files. we will need to leverage < (reading from stdin)
```text
./main < input.txt
-module(example).
-export([main/0]).
main() ->
case io:get_chars("", 1) of
eof ->
ok;
Char ->
io:format("~p~n", [Char]),
main()
end.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int ch;
while ((ch = getchar()) != EOF) {
printf("%c\n", ch);
}
return EXIT_SUCCESS;
}