Modify line in text file without using input line # in "C"

Is there a way to modify a line without requesting the user to input the line number, meaning without using scanf("%d",&lineNr); in code?

Example of a text file:

1
2
3
4
5
John      5
Michael   7
George    9
Robert    1
Lisa      15


Okay.. I just want to modify only the numbers and the name to remain as they are, without using in code input line # to modify.

I wanna use this for a game and to store the score.. so after the game ends the score is modify, but I don't have to ask user to input a line # from the list to modify.
What is known is just the current Name of who is playing the game.

Any ideas ? :|
Last edited on
Store the high scores in a file, read them into two arrays when the game starts. One for the names, the other for the scores. When the current user finishes the game search for their name.

If found check if the associated score is less than their current store. Change the score if needed.

If the user is a new player (name search fails) add their name and score to the arrays.

Write out the new high scores tables and Bob's Your Uncle.

If'n you were coding in C++ doing this could be simplified. With std::set, std::string, etc.
Last edited on
I know.. I'll be starting C++ on later, now I really need to do this in the hard way, even if it seems to be easy. I need a better understanding of C before starting something else. My age is not of the youngest, and I need to stick with what I learn until now... To do a summary of what I have to do is easy, I mean I know the steps and what to do first and what after, but from thinking and doing are great steps, My problem is that I can't figure out how to create a new project and try to do this and that, I mean I don't wanna do this on the current project before I really know what I have to do, but the code I have is huge and reproduce this part on a new project is really a pain in the a**. Dohh.. Thanks Furry Guy for now , I'll try to remove all the cache in my brain :D ... and figure out doing this in a fresh project.
Should I learn C before learning C ++? - Stack Overflow - https://stackoverflow.com/questions/598552/should-i-learn-c-before-learning-c

C and C++ share a lot of the same syntax and language semantics, but they are different languages. Procedural vs. OOP requires a different "mental map" of how to construct programs.

A well-written C program can compile without a problem much of the time with a C++ compiler. The reverse MAY not true. If you don't use C++ specific language features or libraries.

And no, writing C programs is NOT "the hard way." Just a different way, without the tools that C++ brings to the toolbox. C++ uses a lot of what C offers to the programmer, with some exceptions.

Five Popular Myths about C++ -- by Bjarne Stroustrup - https://isocpp.org/blog/2014/12/five-popular-myths-about-c-bjarne-stroustrup

I recommend reading the postscript at the above link first and then read about each myth (parts 1, 2 & 3).

FYI, Bjarne Stroustrup is the guy who invented C++.

Being a self-taught (and still learning) programming hobbyist I very much prefer the amount of tools C++ offers when crafting programs, compared to the smaller C toolbox.

That doesn't mean I won't use C concepts in a C++ program if/when doing so makes the task easier to understand and write code that is robust.
Last edited on
I learned c++ long ago, and it was taught as a mix of C and C++ back then.
here are some pros and cons ..

pros to C first..
you will learn to do things you don't need to do. How to make a linked list from scratch. Pointers and dynamic memory. Dealing with arrays where you lack an assignment operator or size() function that vectors provide in c++. Working with the preprocessor. Low level tools.

Those skills will be useful when you learn other languages that lack high level built in containers and objects. Eg, if you had to work in basic, it would be procedural and you would have to do some raw things that c++ would not have prepared you for.

The cons are the reverse..
you will learn a bunch of stuff you don't need to work in c++, and SHOULD NOT do in C++ even if it works there. Your c++ code will suffer because you think you know how to do something and don't realize its done for you without having to roll it out yourself. You have to second guess yourself every time you do something "wait, does c++ do this already without my home-made code?" is something you have to ask a lot until you learn what is available.

C isnt useful for trying to learn it first then move to c++, it actually makes things worse for you. But C is a GREAT language and knowing it has merits.
Last edited on
C++ was purposefully designed to be a better C, and it largely succeeds. However, it has a huge collection of potential foot guns (features) which must be shot with care. Lots of features are massively overused.

For example, just yesterday I tried (and probably failed) to stop someone from writing a horrible polymorphic forward iterator thing when what they really needed was float*. Their code has an interesting implementation, but it's awful in context. So this person shot themselves in the foot like many before them -- it's a bloody pattern.

This is less a language-design issue than a community issue, but if their code base was C they probably would have settled on float*.

So there's pros and cons.
Last edited on
I just want to modify only the numbers and the name to remain as they are


Unless you are using fixed-sized records, then modifying part of a sequential file is fraught with problems. You can't just delete parts and insert. You can only overwrite. You can overwrite say 5 with 7, but if you then overwrite 7 with say 13 then the 7 gets overwritten by 1 and the char following 7 (possibly \n) gets overwritten by 3. Now you have concatenated 2 lines. If you want to do this, then originally create the file with the maximum number of chars that's going to be required for a field (eg 5 for a score etc). Then when you come to change the score, you overwite these 5 bytes with the new score. It's probably easier to read the whole file, update a score and then write the whole data back to the file as per Furry Guy's post (although I'd be tempted to use a struct and one array of this type).
If we assume that the file has the format <name> <2spaces><score> where name is 12 chars left justified and score is 5 digits right justified, then to change the score consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void sdisp(FILE* fs)
{
	rewind(fs);

	for (char line[256] {}; fgets(line, 255, fs) != NULL; printf(line));
	puts("");

	rewind(fs);
}

bool smod(FILE* fs, const char* name, int newscore)
{
	rewind(fs);

	int score = 0;

	for (char fname[15] {}; fscanf(fs, "%12s%d", fname, &score) != EOF; )
		if (strcmp(fname, name) == 0) {
			fseek(fs, -5, SEEK_CUR);
			fprintf(fs, "%5d", newscore);
			fflush(fs);
			return true;
		}

	return false;
}

int main()
{
	FILE* fscore = fopen("scores.txt", "r+");

	if (fscore == NULL) {
		puts("Cannot open file");
		return 1;
	}

	sdisp(fscore);
	if (smod(fscore, "George", 19))
		puts("Modified");
	else
		puts("Not found");

	sdisp(fscore);
	fclose(fscore);
}



John          5
Michael       7
George        9
Robert        1
Lisa         15

Modified
John          5
Michael       7
George       19
Robert        1
Lisa         15


may also write/read in binary mode.

> I don't wanna do this on the current project before I really know what I have to do,
good, draw some diagrams and write pseudocode

> but the code I have is huge
version control
you fucked up, rollback

> and reproduce this part on a new project is really a pain in the a**
isolate your new feature
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
define score as{
	string: name
	integer: value
}

read_scores():
	input:
		string: filename
	output:
		array(score): scores

find_score_index():
	input:
		array(score): scores
		string: name
	output:
		integer: index

write_scores():
	input:
		string: filename
		array(score): scores

Topic archived. No new replies allowed.