iamanapprentice
iamanapprentice

Reputation: 421

editing file using fseek

can you help me figure out what's the problem in my code.. i wanted to edit a specific line.... thnx

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

int main (){
    char arr[50];
    char arr2[50];
    char arr3[50];     
    FILE *stream = NULL;
    FILE *stream2 = NULL;
    stream = fopen("studentinfo.txt", "rt");
    stream2 = fopen("studentinfo2.txt", "w+");
    char* token;
    char dlm[] = ",";

    printf("Enter student id: ");
    scanf("%s", arr2);
    printf("New student id: ");
    scanf("%s", arr3);
    while(!feof(stream)){
       fgets(arr,100,stream);
       fprintf(stream2,"%s",arr);
       token = strtok(arr,dlm);
       if(strcmp(arr2, token)==0){
       fseek ( stream2 , 0 , SEEK_CUR );
       fputs ( arr3 , stream2 );
       }
    }
    fclose ( stream2 );
    fclose ( stream );
    getch();
}

Upvotes: 0

Views: 837

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

You cannot "edit specific lines". You can replace the bytes that are currently in the file, but if you need to replace with fewer or more bytes then you need to rewrite the rest of the file after them.

Upvotes: 5

Related Questions