473,396 Members | 1,917 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

FILE as parameter to function

131 128KB
Expand|Select|Wrap|Line Numbers
  1. void foo(FILE *f1, FILE **f2)
  2. {
  3.     fputs("...",  f1);
  4.     fputs("...", *f2);
  5. }
  6.  
  7. int main(void)
  8. {
  9.     FILE *fp1 = fopen(...),
  10.          *fp2 = fopen(...);
  11.  
  12.     if(fp1 && fp2)
  13.     {
  14.         foo(fp1, &fp2);
  15.         ...
  16.     }
  17.     ...
  18. }
Forever, I've passed FILE objects into functions like the first parameter; I've never had an issue reading or writing files using that form - no file errors, no compiler warnings, etc. Recently, I saw the second paramter form, and wondered why that was?

I still don't quite get this part of pointers. What's the second parameter form doing differently than the first when the first version *appears* to work as intended?? I'm quite confused now.

TIA
May 17 '13 #1

✓ answered by weaknessforcats

OK. Suppose you are writing a log file system where when the log reaches a set limit, you close the current log, then create a new one. the new log has its own FILE so you get the address of this new FILE into the FILE* used by the rest of the logging system. To do that you need the address of the FILE* used by everyone else. That would be a FILE**. Your function would need that FILE** should it become necessary to start a new log file.

Expand|Select|Wrap|Line Numbers
  1. void CreateNewLog(FILE** currentlog)
  2. {
  3.     /* close current log file */
  4.     fclose(*currentlog);        
  5.  
  6.     /* create new log*/
  7.     FILE* fp = open(etc...);
  8.  
  9.     *currentlog = fp;
  10. }

6 3029
weaknessforcats
9,208 Expert Mod 8TB
The first argument, FILE* is the address of a FILE struct. The function cannot change the address in the pointer. It has to use the FILE provided by address.

The second argument is the address of a FILE*. This allows the function to change which FILE* it is using by changing the address in the FILE*.

You use pointers to make run time decisions and to pass info to,and retreive answers from functions. You can't just pass in your variable since a copy is made and the copy can only update the copy. The copy is deleted when the function completes taking the change with it. So instead you pass in the address of the variable and the function makes the change at that address. The variable at that address lives on after the function completes thereby preserving the change.
May 17 '13 #2
divideby0
131 128KB
First and foremost, thank you wfc.

The second argument is the address of a FILE*. This allows the function to change which FILE* it is using by changing the address in the FILE*.
I follow that the pointer to the FILE struct cannot be changed, but I don't quite follow what the FILE* can do in practice.

If a declaration was

Expand|Select|Wrap|Line Numbers
  1. void some_function(FILE **ptr)
  2. {
  3.    *ptr = fopen("..."); ?? 
  4. }
  5.  
  6. // in main
  7. FILE *fp = NULL;
  8.  // would a file be opened here??
  9.  
  10. some_function(&fp);
  11. // would it be opened in the function??
  12. // is it to point to an exiting * to FILE struct??
  13.  
I don't understand how this mechanism works at all. I've only ever known opening a FILE* in main and passing this to whatever functions I needed, and then closing it in main.

Could you post a brief example of how this would work? A visual may help me better understand it.
May 18 '13 #3
weaknessforcats
9,208 Expert Mod 8TB
OK. Suppose you are writing a log file system where when the log reaches a set limit, you close the current log, then create a new one. the new log has its own FILE so you get the address of this new FILE into the FILE* used by the rest of the logging system. To do that you need the address of the FILE* used by everyone else. That would be a FILE**. Your function would need that FILE** should it become necessary to start a new log file.

Expand|Select|Wrap|Line Numbers
  1. void CreateNewLog(FILE** currentlog)
  2. {
  3.     /* close current log file */
  4.     fclose(*currentlog);        
  5.  
  6.     /* create new log*/
  7.     FILE* fp = open(etc...);
  8.  
  9.     *currentlog = fp;
  10. }
May 18 '13 #4
divideby0
131 128KB
You are always so helpful even if I don't quite get it the first, fifth or hundredth time. :)

It sounds like this would be for something like a server or high volume application. If so, that would certainly explain why I've never seen it before.

If I understand you correctly, would this code be right? "status" returned 0 for each iteration and each file was created with all but the last having data written to it.

I'm guessing the last file was created within the function, but returned to the caller without writing any data since it hadn't been assigned to *currentlog before the write operation?

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. int CreateNewLog(FILE** currentlog, const char *fname, const char *fmode)
  4. {
  5.     FILE* fp = fopen(fname, fmode);
  6.  
  7.     if(fp && *currentlog)
  8.     {
  9.         fprintf(*currentlog, "%s %s", fname, fmode);
  10.         fclose(*currentlog);
  11.         *currentlog = fp;
  12.         return 0;
  13.     }    
  14.     else
  15.     {
  16.         *currentlog = NULL;
  17.         return -1;
  18.     }
  19. }
  20.  
  21. int main(void)
  22. {
  23.     char flist[BUFSIZ];
  24.     int i;
  25.     FILE *fh = fopen("file00", "w+");
  26.  
  27.     for(i=1; i <= 10; ++i)
  28.     {
  29.         sprintf(flist, "file%02d", i);
  30.         printf("status: %d\n", CreateNewLog(&fh, flist, "w+"));
  31.     }
  32.  
  33.     if(fh)
  34.         fclose(fh);
  35.  
  36.     getchar();
  37.     return 0;
  38. }
May 18 '13 #5
weaknessforcats
9,208 Expert Mod 8TB
It looks like you have the idea. I would use an fprintf to log the create.
May 18 '13 #6
divideby0
131 128KB
Thank you; I appreciate your explanation and time.
May 18 '13 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: (-: Dan :-) | last post by:
hi everybody suppose I have a function in a DLL function F1(var1, var2, var3) where var2 and var3 are optional parameter with default value (for exsample "-1") I create a new instance of...
3
by: Boris Sargos | last post by:
Hi, suppose we have these two functions (not very interesting, but this is for clarity) : -) a function Primitive that computes at t the primitive of a function f : double Primitive (...
4
by: Helge Stenstroem | last post by:
Say I have a function def f(filename): result = openFileAndProcessContents(filename) return result Can that function be unit tested without having a real file as input? Something along the...
3
by: Earl Purple | last post by:
This is a simple function to split a file into multiple files (archives) of a fixed size. The last one will contain any remaining bytes. Here is the implementation: #include <cstdio>...
5
by: Joe | last post by:
Hi, I like to know what do you specify in the function parameter (in the function implementation) if you want the string that you pass in with the function call to be changed while its in the...
5
by: MLH | last post by:
Searching at http://support.microsoft.com/search/?adv=0 for Access 97 and "templatefile" returns the following: There are no documents that match your search for "templatefile" Has anyone ever...
4
by: cupa | last post by:
Hi, is it posible to execute script from file within function (sql or pl/sql or ...)
2
by: CFAN | last post by:
I have written a variable parameter function: APR_DECLARE_NONSTD(apr_status_t) sas_strcat(char *buffer,size_t * buffer_len ,... ) { char *cp, *argp; apr_size_t saved_lengths; apr_size_t...
6
by: Michael | last post by:
I need to copy a huge file (around 300Mb) from a mapped network drive to another. I have created a console application and used System.IO.File.Copy function. But I want to know the process of...
7
by: bcpkh | last post by:
Hello All Received a header file from a supplier that defines an interface to implement but it's giving me a problem, I reproduce the general structure of the header file below; #ifndef XYZ_H...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.