So I have a project I am doing and I have created a program that allows the user to write to a file, as shown below:
#include <stdio.h>
#include <stdlib.h>
FILE *fd;
FILE *fw;
struct store
{
char Word[512];
char NWord[512];
}
stock;
struct store2
{
char Definition[512];
}
stock2;
char done='y';
int count=1;
int c=0;
int d=0;
int main(void)
{
fw=fopen("Test Z W.txt","w");
fd=fopen("Test Z D.txt","w");
do
{
printf("Word %d: ",count);
gets(stock.Word);
while((c= getchar()) != '\n' && c != EOF);
printf("Definition %d: ",count);
gets(stock2.Definition);
while((c= getchar()) != '\n' && c != EOF);
fprintf(fw,"%s\n", stock.Word);
fprintf(fd,"%s\n", stock2.Definition);
count=count+1;
system("cls");
}
while (count<11);
fclose(fd);
fclose(fw);
return 0;
}
this code is fine, however, I would like to expand it so that there is an option to edit just one chosen line, rather than wiping the entire file and writing all of the contents again.
All I have to work on is using How do you write to a specific line of a txt file in C?
Which wasn't very helpful since I couldn't take an answer and import it to my code, either way all I need is something where an error such as the one below, can be fixed easily.
1
2
Three
4
5
6
7
8
9
10
Where the user will automatically be asked which line they want to edit.
This program will open a source file (which may have error,i called it source.txt*) and keeps reading it character by character and write to new file (target.txt) untill (EOF) is found.But it will stop at the specific line and will ask user to input some data which will be written in place of error(error line from source file) in new text file( target.txt).
so at the end you will get target.txt file free from errors. Open and check it.
In this program i have assumed that we want to replace only single character at line 3.but you can change this operation to replace it with string,float or integers etc.
Here is the output:-
Enter Line Number Which You Want 2 edit: 3
Enter input to store at line 3: 3
Congrates...Errors Edited Successfully.
contents of target.txt:-
1
2
3
4
5
6
7