jynlix said:
Hmmm, C99.
#include <stdio.h>
#define MAX 30
int main(int argc, char** argv)
{
FILE* pf; //declare a file pointer first
int iNums[MAX];
int i = 0;
if (argc != 2)
{
printf("Usage:%s filename\n", argv[0]);
return 1;
}
You test the argument count here, but you do not use any of
the arguments. The Usage you indicate implies that a filename is
to be supplied, but you do not use the argument as a filename.
As the Usage message is wrong, it should be corrected. As you
never actually use the arguments and as it is pointless to do
the test you do, the test against argc should be omitted, and
probably argc and argv should be omitted from the prototype of main().
Also, when you are writing out an error message, you would
normally send it to stderr, not to stdout.
//open a file
if ((pf = fopen("in.txt", "r")) == NULL)
{
printf("Unable to open the file, pls check it!\n");
Again, error messages to stderr. It would usually be a good idea to
indicate which file is the problem, and to indicate a reason if
one can be deduced.
The standard assigns definite meanings to returning 0 from main
and to returning 1 from main, but returning anything else from main
has implementation-defined results.
}
//read some numbers from the file
while (fscanf(pf, "%d", &iNums) != EOF)
{
fprintf(stdout, "%d ", iNums[i++]);
fprintf() is not -usually- used with stdout: -usually- printf() is
used instead.
Your code assumes that there is no more data in the file than was
originally indicated, and assumes that there is no problem with the
file. If there is a character in the file which does not form part
of an integer, then the fscanf() will return 0, and your code will
think a value has been read, and will try to print out the
uninitialized value from iNums... and then will loop back and
try to print out the next uninitialized location from iNums,
and so on, continuing onward until the operating system generates
a memory fault from attempting to access entries of iNum that lie
beyond the declared array size. If the operating system never notices,
then eventually i will overflow back to 0, but that just means it
will print the input values over again; the program might never
terminate.
}
//remember to close it
fclose(pf);
return 0;
}
i hope this is useful
I notice that you did not use any the properties of C99 that
ae not also in C89, with the exception of the comment style.
The portability of your code to those who still use C89 would
have been increased if you had used traditional comment style
instead of C99 comment style.