S
subramanian100in
Consider the following program:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: <program-name> <text-file>\n");
exit(EXIT_FAILURE);
}
FILE *fp;
if ((fp = fopen(argv[1], "r")) == NULL)
{
printf("Could not open input file :%s:\n", argv[1]);
exit(EXIT_FAILURE);
}
if (fseek(fp, 0L, SEEK_END) == 0)
printf("fseek successful\n");
else
printf("fseek failed\n");
long int size = ftell(fp);
printf("filesize = %ld\n", size);
fclose(fp);
char a[size+1];
a[size] = '\0';
if ((fp = fopen(argv[1], "rb")) == NULL)
{
printf("Could not open input file :%s:\n", argv[1]);
exit(EXIT_FAILURE);
}
fread(a, size, 1, fp);
if (ferror(fp))
{
printf("fread failed\n");
fclose(fp);
exit(EXIT_FAILURE);
}
fclose(fp);
printf("%s", a);
return 0;
}
Suppose the name of the file is tmp.c
I compiled this program with gcc under Redhat Enterprise Linux with
the command
gcc -std=c99 tmp.c
It compiles well. I ran it with the command
$./a.out tmp.c
It runs successfully.
My questions:
1) Is the usage of ftell above correct ?
2) In the second fopen, I have used "rb" for the mode ie I am opening
the text file in binary mode and then using fread. Will this always
work ?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Usage: <program-name> <text-file>\n");
exit(EXIT_FAILURE);
}
FILE *fp;
if ((fp = fopen(argv[1], "r")) == NULL)
{
printf("Could not open input file :%s:\n", argv[1]);
exit(EXIT_FAILURE);
}
if (fseek(fp, 0L, SEEK_END) == 0)
printf("fseek successful\n");
else
printf("fseek failed\n");
long int size = ftell(fp);
printf("filesize = %ld\n", size);
fclose(fp);
char a[size+1];
a[size] = '\0';
if ((fp = fopen(argv[1], "rb")) == NULL)
{
printf("Could not open input file :%s:\n", argv[1]);
exit(EXIT_FAILURE);
}
fread(a, size, 1, fp);
if (ferror(fp))
{
printf("fread failed\n");
fclose(fp);
exit(EXIT_FAILURE);
}
fclose(fp);
printf("%s", a);
return 0;
}
Suppose the name of the file is tmp.c
I compiled this program with gcc under Redhat Enterprise Linux with
the command
gcc -std=c99 tmp.c
It compiles well. I ran it with the command
$./a.out tmp.c
It runs successfully.
My questions:
1) Is the usage of ftell above correct ?
2) In the second fopen, I have used "rb" for the mode ie I am opening
the text file in binary mode and then using fread. Will this always
work ?