How to write an int variable to a file in c?
How to write an int variable to a file in c?
fwrite() or some other write method, using a binary mode of access.
Mainframe assembler programmer by trade. C coder when I can.
thank you.
I had the same problem. Here is how I solved it this works for 2 variables wich is harder than one.
1. Create a file on your C drive called "file.txt" with the following text:
2.Then add the following code to read those two variables, add 3 to each, and then write it to file again.Code:var1 = 1; var2 = 2;
3.Compile this and then run it the program should dislplay:Code:#include<stdio.h> main() { int var1; int var2; FILE *fp; FILE *fw; char *char1; char *char2; char1="var1 = "; char2="var2 = "; fp=fopen("c:\\file.txt", "r"); fscanf(fp, "var1 = %d; var2 = %d;", &var1, &var2); printf("%d\n", var1+3); printf("%d\n", var2+3); var1= (var1 + 3); var2= (var2 + 3); fclose(fp); fw=fopen("c:\\file.txt", "w"); fputs(char1, fw); fprintf(fw, "%d; ", var1); fputs(char2, fw); fprintf(fw, "%d;", var2); fclose(fw); }
4
5
and the next time you run it:
7
8
and so on and you can change the numbers and it will stay to the same pattern.
Note: You may have to adjust the location based on your set up. And if your running windows make shure the application isnt set to close on exit under properties.
C-Compiler
always remember: DOS wasnt written in a day...
This works I have used this method in other programs for things such has highscores.
I program using Visual Studio Professional 2008. I have little experience, I'm self taught. I started basic C in early March 2008 with a 1987 compiler and C++ this October with Visual Studio. I normally program in Visual C++ creating form programs. My current project is a simple game where I hide a dot and you have to find it in different random sinerios.
My Catchphrase:
DOS wasn't written in a day...
C-Compiler, I think the original poster (OP) meant how to do it in binary.
Also, it's Amateur Programmer, not Amature Programer.
Mainframe assembler programmer by trade. C coder when I can.
Yes, I was looking for binary mode and fwrite did it well.
That is just how I figured to do that and it works fine for me, and Ill correct the spelling.
I program using Visual Studio Professional 2008. I have little experience, I'm self taught. I started basic C in early March 2008 with a 1987 compiler and C++ this October with Visual Studio. I normally program in Visual C++ creating form programs. My current project is a simple game where I hide a dot and you have to find it in different random sinerios.
My Catchphrase:
DOS wasn't written in a day...