Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Working with files in C 1

Status
Not open for further replies.

sirbu

Programmer
Sep 15, 1999
15
0
0
RO
Let’s say that I have a variable

char filename[12] = "xxxxxxxx.xxx";

and a function who opens a file.

void OpenFile( char *fname)
{
FILE *f;
f = fopen(fname,"w");
if( f == NULL )
{
printf( "File could not be opened\n" );
exit(1);
}
/* Follows code that reads from the file */

}

How do I must write the previous function and what she has to return (instead of void) so in other function I can use the same file that is already open. What arguments must I pass to the other function?
Let me be more precise, I want to write a function that reads a part of the file, another function that reads from that point forward a.s.o.

Thank you

P.S. No polemics please, just straight answers (if possible)
 
By the way, if you're using file format 8+.+3 the correct declaration for filename is char filename[13].

FILE* OpenFile( char *fname)
{
FILE *f;
f = fopen(fname,"w");
if( f == NULL )
{
printf( "File could not be opened\n" );
exit(1);
}
/* Follows code that reads from the file */
return f;
}
John Fill
1c.bmp


ivfmd@mail.md
 
u will have to use low level system commands, namely open to open the file, lseek to get total number of bytes read, and read to read the contents of the file.

so, when u read the contents 1st u will get the total number of bytes read, u can pass this long int value as a parameter to the function that wants to read the file from that position. In this function, there will be an lseek call that jumps straight to that position, and u can do u'r reading or whatever u want to do from there.

 
No, from the description provided, the standard functions found in <stdio.h> are adequate. Furthermore, reading from a FILE * automatically changes the position of the associated file descriptor, so there's no need to use &quot;seek&quot; functions such as lseek() to do what the OP wanted.
Russ
bobbitts@hotmail.com
 
You can declare the File pointer globally ( or with in the main funcion, if there is no scope problems)

Then passs the file pointer as an argument to your functions.

void first_read(FILE *);
void second_read(FILE *);

int main()
{
FILE *fp;
fp = fopen(&quot;file name&quot;, &quot;mode&quot;);
first_read(fp);
second_read(fp);
...
return 0;
}

void first_read(FILE *fp1)
{
...
}

void second_read(FILE *fp2)
{
...
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top