I've been trying to read and write from a file at the same time and I'm trying to substitute all the tabs in the content of text.txt to be turned into spaces. This is my code:
int main()
{
FILE* filePtr = fopen("text.txt", "w+");
char c;
c = fgetc(filePtr);
fpos_t num;
while(c != EOF)
{
if(c == '\t')
{
fgetpos(filePtr, &num);
num--;
fsetpos(filePtr, &num);
fputc(' ', filePtr);
}
c = fgetc(filePtr);
}
}
The content of text.txt is as such:
Hi \t my \t name \t is \t jack!
When I run this code, my output in the text.txt file is just blank space. There are no characters there. What should I do so that the substitutions work out as intended?
There are three main problems with your code:
Opening the file with mode "w+"
truncates the file (removes all contents). You can both read and write to it, but the original contents are lost. Mode "r+"
would open it for reading and writing without changing the contents, and with the file position initially at the beginning of the file.
It is not safe to perform arithmetic on a value of type fpos_t
. It's anyway needless; there's an easier way to move the file position a relative amount.
You do not close the file when you're done.
This variation on your code works for me:
#include <stdio.h>
int main(void)
{
FILE* filePtr = fopen("text.txt", "r+");
char c;
while((c = fgetc(filePtr)) != EOF)
{
if(c == '\t')
{
fseek(filePtr, -1, SEEK_CUR);
fputc(' ', filePtr);
}
}
fclose(filePtr);
return 0;
}