I am used to C in competitive programming. Below is my C temaplate:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a;
cin >> a;
cout << a * 4 << " " << a * a;
}
I want a safe equivalent in C, I tried to find it on my own, but found many versions.
I have found the following equivalent, is that the one you'd recommend?
#include <stdio.h>
int main() {
FILE* inp = freopen("input.txt", "r", stdin);
FILE* out = freopen("output.txt", "w", stdout);
int a;
scanf("%d", &a);
printf("%d %d", a*4, a*a);
fclose(stdout);
}
Is this safe and optimal?
CodePudding user response:
The second code snippet is equivalent to the first one, except that you ignore the return value of freopen
in the former, and save it in the later.
If the file is successfully reopened, the function returns the pointer passed as parameter "stream", which can be used to identify the reopened stream. Otherwise, a null pointer is returned. On most library implementations, the errno variable is also set to a system-specific error code on failure.
I'd say the second one might be
more secure, as freopen
returns NULL
on failure, and inp
and
oup
can be used to check for an error.
If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.
independently of whether that stream was successfuly closed or not suggests that it could remain open, or be in some error state. But failure to close the original stream shall be ignored.