Hello, Jarren!
Code follows below. Hope it helps/is useful. Just drop it into the
main file of a new console app and all should go well.
Please tell me if I've overlooked anything or you're curious about somethin=
g.
-Lukas
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
printf("File name: ");
char fname[80];
fgets(fname,sizeof(fname),stdin); // grab file name from user
fname[strlen(fname) - 1] =3D 0;
// put a null character at the last place of the string to ensure
that display works properly
// (to find out why, comment that line out and recompile)
FILE *fp =3D fopen(fname,"r"); // Open the file as an ascii read-only fil=
e
if (!fp) return 0; // File doesn't exist/can't be accessed/etc. =20
char first[5];
memset(first,0,sizeof(first)); // Ensure that the string will be blank
fread(first,sizeof(first)-1,sizeof(char),fp); // Read three
characters in from the file
first[strlen(first)-1] =3D 0; // as like last time (9th line)
printf("First %d characters of file: %s\n",sizeof(first)-2,first);
fseek(fp,0,SEEK_END); // Jumps to end of file
unsigned long int fsize =3D ftell(fp); // Returns position in file
printf("Size of file: %ld\n", fsize);
fseek(fp,-2,SEEK_END);
// Jumps back two from current position in file. Could also use SEEK_CUR
// as we're at the end
// of the file, but this works because we've jumped to the end.
char last[4];
memset(last,0,sizeof(last)); // same as before
fread(last,sizeof(last)-1,sizeof(char),fp); // read two characters from f=
ile
last[sizeof(last) - 1] =3D 0; // same as before
printf("Last %d characters of file: %s\n\n",sizeof(last)-2,last); =20
fclose(fp); // close the file
system("PAUSE");=09
return 0;
}
On 6/17/05, Jarren Long <vb...@gm...> wrote:
> Ok, what I need to do is open up a file and get the exact number of
> bytes in the file, including the first three and the last two
> characters, all stored in seperate variables. Example:
>=20
> //start file.txt
> This is a simple text file
> //end file.txt
>=20
> I want to be able to get this:
> Thi
> 36
> le
>=20
> I have no clue where to start. Any help would be great
>=20
> Cheers!
|