Click to See Complete Forum and Search --> : Removing "N" bytes from file..???


rtos
March 15th, 2005, 11:29 PM
I have the following question :

how to remove "N" number of bytes from a
opened text or binary file?

any idea?

jawadhashmi
March 15th, 2005, 11:46 PM
FILE* hFile;
hFile = fopen("c:\\numbers.txt", "r");
if(hFile)
{
char szText;

while(fread(&szText, sizeof(char), 1, hFile) > 0)
{
printf("%c",szText);
}
fclose(hFile);
}


You can open a file and read character by character. Open another file and write the desired data to the new file.

You also can use fstream for better control.

cilu
March 16th, 2005, 02:54 AM
Well, you want to remove N bytes from a file, starting at byte M.

* read the first M bytes from the file and write them in a temporary file
* read the next N bytes and skip them (do not copy them to the temp file)
* read the rest of the file and write them to the temp file
* delete the original file
* change the name of the temp file to the name of the orginal file (assuming they are in the same folder)

rtos
March 16th, 2005, 03:05 AM
well . actually i had put one Q under the thread called "File Splitting".
There were no replies for that.

My purpose is :

1.Read first 200 bytes from a file (File A ) into a buffer.

2. Remove first 4 bytes from that buffer and write to a new file (File B).

3. Read next 200 bytes from the orginal file (File A) .

4. Perform step 2 .

5. Perform this until the end of the orgimal file (File A).

Did u get an idea what i wanted to do?

jawadhashmi
March 16th, 2005, 03:28 AM
You can see the code above to read the data from the file. You can read 200 bytes at a time from the file.
open the another file and start writting to it from 5th byte.
repeat the reading and writting operation untill there is no more data in the file.

are you looking for the complete program?

rtos
March 16th, 2005, 03:34 AM
i am in the learning stage of C/C++.
If u can give complete program with comment and explanation
it will be greatly helpful to learn C file operations.

thanks.

jawadhashmi
March 16th, 2005, 04:17 AM
FILE* f_in;
FILE* f_out;
//open file for reading
f_out = fopen("C:\\file1.txt", "r");
//open file for writting
f_in = fopen("c:\\file2.txt", "a+");
char szData[200] = "";

//read the file to the end
int read = 0;
while( (read = fread(szData, sizeof(char), 200, f_out)) > 0)
{
if(read > 4)
{
fwrite(&szData[4], sizeof(char), strlen(szData)-4, f_in);
}
}
//close the reading file
fclose(f_out);
//close the writting file
fclose(f_in);


Hopefully this will help you