-
if not exist, failed
Hello
I try a function "if not exist" but this will give my Warnings, please what would meant this warnings?
Code:
#include<stdio.h>
int main() {
FILE *fname;
if (fname = fopen("a.txt", "r")) {
fclose(fname);
printf("file exists");
} else {
printf("file doesn't exist");
}
}
to compile using "geany" and "GCC" for Windows.
Warning from Compiler
Code:
gcc -Wall -c "ifex.c" (im Verzeichnis: C:\Temp\tcc)
ifex.c: In function 'main':
ifex.c:4:8: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
5 | if (fname = fopen("a.txt", "r")) {
| ^~~~~
Kompilierung erfolgreich beendet.
please, if there problems with the GCC Compiler ? i see also
that in the meantime the Compiler Option i need to change from GCC 2 g++, and then the file will blow up over 2-3mb, for 10 lines Code?
-
That warning is legit. The compiler thinks you meant to use '==' instead of '='.
Two options:
Code:
...
if ((fname = fopen("a.txt", "r"))) {
...
or
Code:
#include <stdio.h>
int main(void) {
FILE *fname = NULL;
fname = fopen("a.txt", "r");
if (fname != NULL) {
fclose(fname);
printf("file exists");
} else {
printf("file doesn't exist");
}
return 0;
}
-
Thanks Rstanley
I made your changes and are running very well thanks meny time.
Strange thing are also, i uninstall Geany my Compiler Environment, and install after that codeblocks, here are running both version my&our without any Warnings.
I would thanks also for your fast answer!
Regards
-
Or see this example.
Code:
/** opnclose.c */
#include <stdio.h> /* printf, fopen, fclose */
#include <stdlib.h> /* exit */
#define READ "r"
int main(int argc, char *argv[])
{
FILE *fz;
if (argc != 2)
{
printf("\n\nSyntax: opnclose datei[.ext]");
exit(0);
}
if ((fz = fopen(argv[1], READ)) == NULL)
printf("\n\nFailure:could not open file %s\n", argv[1]);
else
{
fclose(fz);
printf("\n\nFile %s closed.", argv[1]);
}
return 0;
}