1

In my problem I was using fseek() function to read a character from the 4th position. After that I wanted to write a new character after that position where the file pointer is pointing to. As after the first call of fseek() function my pointer is in the 5th position I wrote the fputc() function to write a new character. But it is not showing any effect on the file. However, when I wrote another fseek() function before fputc() then the code works just fine. My Question is why do I need to add the fseek() function again? I also checked through SEEK_CUR to ensure that my pointer was in the 5th position. NB: my file contains "Modern technology is all about efficiency and speed;". After successfully run my code I didn't see any changes in my file

#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *fp;
char ch;
char c[100];

fp = fopen("file12.txt", "r+");
if (fp == NULL) {
    printf("ERROR");
    exit(1);
}

fseek(fp, 4, SEEK_SET);
printf("%c", fgetc(fp));

// fseek(fp, 0, SEEK_CUR);
fputc('M', fp);

fclose(fp);
return 0;
}
  • Unrelated, but what purpose do `ch` and `c` serve in this code? Kindly remove all unrelated code. – Harith May 22 '23 at 19:09
  • Because you are changing modes between reading and writing. Stream file I/O is buffered, not read/written on a per call basis, so handling the in memory buffer needs to be done as well as positioning. – Avi Berger May 22 '23 at 19:11
  • @Haris c and ch are indeed unused, and if you enable warnings at least gcc complains about them. – janneb May 22 '23 at 19:11

0 Answers0