-
December 26th, 2009, 05:04 PM
#1
Importing Variables From Outside File
I'm looking to be able to import variables from an outside source. If i were to create a file that said:
var1 = 15
var2=C:/Files/run.exe
How would i accomplish this? What would be the best alternative if this is not possible.
-
December 26th, 2009, 07:03 PM
#2
Re: Importing Variables From Outside File
One option would be to write and read a structure containing all the required info to/from a ASCII text file.
Code:
#include <stdio.h>
#include <string.h>
struct rec
{
int var1;
char var2[256];
};
int main(void)
{
FILE *f;
struct rec r, t;
f=fopen("myFile.txt","w");
if (!f)
return 1;
r.var1 = 15;
strcpy(r.var2, "C:/Files/run.exe" );
fwrite(&r,sizeof(struct rec),1,f);
fclose(f);
f=fopen("myFile.txt","r");
if (!f)
return 1;
fread(&t,sizeof(struct rec),1,f);
printf("var1 = %d\nvar2 = %s\n",r.var1,r.var2);
fclose(f);
return 0;
}
-
December 26th, 2009, 09:28 PM
#3
Re: Importing Variables From Outside File
urgh. why use out-dated headers when there are perfectly good c++ standard equivalents??
please see <fstream>, <string> and <iostream>
-
December 26th, 2009, 11:48 PM
#4
Re: Importing Variables From Outside File
Originally Posted by Amleto
urgh. why use out-dated headers when there are perfectly good c++ standard equivalents??
please see <fstream>, <string> and <iostream>
Hmmm... Maybe somebody should notify the International Organization of Standards that their C99 C standard is out-dated.
-
December 27th, 2009, 12:39 AM
#5
Re: Importing Variables From Outside File
I'm looking to be able to import variables from an outside source. If i were to create a file that said:
var1 = 15
var2=C:/Files/run.exe
How would i accomplish this? What would be the best alternative if this is not possible.
1. Open the file in question.
2. Read a line from the file as a string
3. Parse that string into an identifier ("var1") and a value ("15")
4. Store the identifier and value using some method (std::map will do nicely)
5. If you're not at the end of the file, go to 2
6. Do something useful with the information you read
7. ...
8. Profit!
Maybe somebody should notify the International Organization of Standards that their C99 C standard is out-dated.
If you're using C++ they're out of date unless you have a specific need for them (usually to support other legacy code).
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|