You are still not explaining it right.
By looking at your readfile() function, it seems that you are storing multiple numbers in you file. The example you gave in your most recent post is about replacing a single number. Now there can be 2 things that you might want to do (or something very similar):
1. User will enter 2 numbers x and y and then replace the number at position x by y
Suppose your file is:
Suppose in the function modifyfile(), then user will enter 3 and then 5.
This will replace the number at 3
rd position by 25(5
2)
This will make your file
2. User will enter x and y and replace every occurrence of x
2 by y
2.
Suppose in modifyfile() the user enters 4 and 7.
The program will replace all occurences of 16 by 49.
This will make your file:
Now you must specify what type of modification you want to do (type 1 or type 2).
For both these types, you would have to
1. Make another file (obviously with a different name).
2. Using a loop
a. read a number from original file (into an int variable, suppose n)
b. modify n if required (by checking its position or value).
c. write n to the other file (don't write if you want to delete instead of modify)
3. Close both files
4. Delete the original file by using remove(char* filename) in <stdio.h>
5. Rename the new file to that of the original file by using rename(char* oldfile,char* newfile) in <stdio.h>
This has to be done if you are using a text file because in text files integers can have varying sizes. For eg, 234 will use 3 bytes while 36543423 will use 8 bytes.
I strongly recommend you to use binary files (as you are storing integers) as this will rid you of this long process, it will be faster and all integers will only occupy sizeof(int) bytes (usually 4 bytes). It will store integers in files the same way it is stored in RAM during a program.
The write() function of ostream class can be used to write an int to a binary-mode-opened file.
This is how the function's prototype looks:
ostream& ostream::write(char* arr,int size);
It writes n characters from the char array arr to the file.
This is how you encode integers and write them to a binary file.
1 2
|
int a=5;
file.write((char*)&a,sizeof(int));
|
Similary you can read from binary files using
file.read((char*)&a,sizeof(int));
Also, in text files, as you don't know the size of an object, you have to continuously read data to reach an object at a given index. But in binary files you can directly jump to the point by using seekg() or seekp().