How to make a piece of code run only one time?

Pages: 12
Okay, I know it sounds crazy, but I really need to know if this is possible. My question first isn't complete, for that I wanna continue here.. So, how do I create a program that in some how a piece of code run only first time and not only, even if you close and run the program again I want that piece of code to not execute. So for example if the first time the program execute let's say it will ask you to input a new password, then if the user closes the program and run it again the program should ask only the password was given at the very first time, and not ask user to set a password again. How to make that program remember that the pass was set and needs to go over that.. ?
even if you close and run the program again I want that piece of code to not execute
You have to store the state (memory of past events) somewhere. Generally, you'd store it in a file on your computer, and read from this file to determine if you need to re-run parts of the code.

If you're storing passwords, you should not store them plaintext. Look into secure password hashing algorithms such as PBKDF2.
https://security.blogoverflow.com/2013/09/about-secure-password-hashing/
Last edited on
Keep on a file a 0 or 1 depending on whether the password has been set.

Could also have a default password and when a check reveals that hasn't been changed, ask for a new password to replace it and allow execution to proceed beyond that point, or keep going with no request required.


For windows, you'd probably use a registry value for state. Maybe also the encrypted password depending upon requirements.
Okay, until here all clear and understand the principle and I thought the same think, to use a boolean flag and store it in a file, and next time program executes reads the file and if the flag is set to true it jumps over the that code and go from that point ahead.
So the first code is to search for that file, and if the flag doesn't exist, I mean a void text.txt to set the first value by asking the user to set a new password. When password is set a true flag is saved on the file and next time the program executes is searching for that flag and if it's true user won't set a new password instead user will be asked for the password it was set for the first time right?
Well to think about the logic of doing things is quite easy, the problem comes when start to write code, maybe for some of you guys is a piece of cake but I'm still a beginner and I like what I'm doing and I am really fascinating, but certain things are very hard to understand, could anyone show me where to start at list how to store that flag on a file ?
Thank you !
Last edited on
Perhaps start with something like this. Encryption is not a high priority at the moment but much needed later on.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <fstream>
#include <string>

int main()
{

    return 0;
}
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
#include <fstream>
#include <iostream>
#include <string>

const std::string passnam = "pass.txt";

std::string getstr(const std::string& prm)
{
	std::string str;

	while ((std::cout << prm) && (!std::getline(std::cin, str) || str.empty())) {
		std::cin.clear();
		std::cout << "Invalid input\n";
	}

	return str;
}

int main()
{
	bool got = false;
	std::string pass;

	std::ifstream fs(passnam);

	if (fs.is_open())
		got = std::getline(fs, pass) && !pass.empty();

	if (got) {
		const std::string newpass = getstr("Enter existing password: ");

		if (newpass == pass)
			std::cout << "Password is " << pass << std::endl;
		else
			return (std::cout << "Incorrect password entered\n"), 1;
	} else {
		fs.close();
		std::ofstream fs(passnam);

		pass = getstr("Enter new password: ");
		fs << pass << std::endl;
	}

	fs.close();
}


For a password, obviously it should be stored encrypted. And where this code displays the entered correct password for testing, the required code would go there.
I see.. makes sens to me.. obviously this is C++ , but I consider this a good example and I'll try to reproduce the same on C,

So thank you seeplus, for your time this example will indeed help me understand how this kinda code works and the logic you used..
do you need to harden it against someone trying to make it run a second time? Or someone wiping out your file etc?

most such programs have a button or something to register first time / new user / etc. The default action is to enter existing user/password.

it is depressingly easy to defeat most local password programs. Networking adds a layer that makes it much more exciting.
Last edited on
Nope, I don't have troubles with no one, I just wanna add this code to a prev. program I posted last days with info file and address.. blah blah and somehow I was thinking to add this piece of code when deleting files so when try to delete something, a password is requested ,
That's why I asked for... anyway my prev. code runs with or without this idea, but was pretty cool stuff to add some extra.
What header should I use for C instead of <fstream>,<iostream> that is specific to C++?
Is <stdio.h> enough.. for seeplus code below?
Last edited on
Should be for fopen(), fscanf(), printf(), fclose(), scanf() etc
you need a file pointer. no other header.

FILE * fp;
fp = fopen(..., "w+"); //look up the second arg, its like printf, you need the right codes there
fprintf(fp, ...);
fclose(fp);

that is for writing, reading is fscanf etc, its very similar to console I/O
Last edited on
Okay.. thank you very much guys for the info.. :)
You also need string.h for string comparison.

Consider for c:

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
50
51
#include <stdio.h>
#include <string.h>

const char cpassnam[] = "pass.txt";

#define MAXPASS 20

void cgetstr(const char* prm, char* str, int csz)
{
	str[0] = 0;

	while (printf("%s", prm) && (!gets_s(str, csz) || *str == 0))
		puts("Invalid input\n");
}

int main()
{
	bool got = false;
	char pass[MAXPASS] = {0};

	FILE* fs = fopen(cpassnam, "r+");

	if (fs != NULL)
		got = (fgets(pass, MAXPASS, fs) != NULL) && (strlen(pass) > 0);

	if (got) {
		char newpass[MAXPASS] = {0};

		cgetstr("Enter existing password: ", newpass, MAXPASS);

		const int l = strlen(pass) - 1;

		if (pass[l] == '\n')
			pass[l] = 0;

		if (strcmp(pass, newpass) == 0)
			printf("Password is %s\n", newpass);
		else
			return (puts("Incorrect password entered")), 1;
	} else {
		if (fs != NULL)
			fclose(fs);

		fs = fopen(cpassnam, "w");

		cgetstr("Enter new password: ", pass, MAXPASS);
		fprintf(fs, "%s\n", pass);
	}

	fclose(fs);
}

Ouu,, oauu , that's awesome. I only have a question

I tried your code but one thing to ask remains .. do I have to define __STDC_WANT_LIB_EXT1__
before I include the <stdio.h> cause I can't use the gets_s(char *str, rsize_t n), I can only use gets(char *str), since this is removed in C11 ?

Or can I use fgets instead ?
Last edited on
You can use fgets as an alternative to gets if you don't have access to the *_s series of functions.
fgets(buffer, BUFFERSIZE , stdin)
ohhh ok ok.. thanks Genado
do I have to define __STDC_WANT_LIB_EXT1__


Yes - for some compilers. You don't seem to need to for MS VS but seems like you need to for your compiler.

As with all bounds-checked functions, gets_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including stdio.h.



If you don't have gets_s() then you can use a #define

1
2
3
4
5
6
7
#ifdef __STDC_LIB_EXT1__
#define __STDC_WANT_LIB_EXT1__ 1
#else
#define gets_s(buff, sz) fgets(buff, sz, stdin)
#endif

#include <stdio.h> 

Last edited on
The code works just fine... I have found only 1 problem

On line 31 const int l = strlen(pass) - 1;

I've changed -1 with -2.

When the pass.txt is saved, after the new password another 2 new lines are created, so when the new password is requested the new pass and the pass won't match.

Thanks for the help again seeplus. :)
Pages: 12