Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Could anyone tell me how to read a file from subroutine in c++?. I can read a file in main program,but i just can't figure out how to do it from subroutine. No book tells how to do it. I need little help asap.
Thanks.

main is basically a subroutine. Write it as you would with main. Rename main to whatever you want to call the subroutine and call it from main. eg
void read_file ()
{
ifstream readme("afile.txt");
char buffer[200];readme.getline (buffer...);
}
main ()
{
read_file ();...
return 0;
}

As cup said, you read a file from inside a subroutine the same as inside main. If you are having problems, it's mostly likely you are messing up on the 'scope' of some variable.
My guess is that you are defining something in main() and trying to use it in the subroutine. For example, in cup's example, if you defined 'ifstream readme(..)' in main() but tried to use 'readme' in the subroutine, it won't work because 'readme' is 'out of scope'. The subroutine doesn't know about 'readme' because 'readme' isn't global and it isn't defined inside the subroutine. You would get an error from the compiler in this case.
The 'scope' of a variable is the portion of the program that the variable is usable in. A simple example:
int iGlobal;
int main() {int iLocalToMain;
.
.
.
}
int mySub() {int iLocalToSub;
.
.
.
}In the example above, the variable 'iGlobal' is called, guess what, a 'global' variable because it is defined outside of any function and thus it's scope is the entire file that it's defined in. That means that you can use it inside any function (main is a function) inside the file. (look up 'extern' if you want global variables usable in multiple files).
The variable 'iLocalToMain' is called a 'local' variable and is only usable inside the function that it is defined in. Thus 'iLocalToMain' is usable only inside the function main.
The variable 'iLocalToSub' is usable only inside the function mySub.
In general, local variables are defined on the 'stack', therefore they cease to exist when you leave a function. If you called the function mySub() and set the variable 'iLocalToSub' to a value, then exited the function, that value would be lost. If you went back into mySub(), the value you put in 'iLocalToSub' would not be there. Also, local variables are not initialized automatically, so you must initialize them if that is necessary.
Global values, on the other hand, keep their values throughout the life of the program and are automatically initialized to 0 unless you initialize them otherwise.
Look up 'static' to see how to make a local variable retain its value between calls to it's function.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |