tcsetattr not restoring echo

The function above for linux doesn't work

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
#if defined( _WIN32 )
    #include <windows.h>
#elif defined( __gnu_linux__ )
    #include <termios.h>
    #include <unistd.h>
#endif

#if defined( _WIN32 )
    // ...
#elif defined( __gnu_linux__ )
void
echo( bool status )
{
    termios oldt;
    tcgetattr(STDIN_FILENO, &oldt);
    termios newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );

    switch( status )
    {
    case true :
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
        break;
    case false :
        tcsetattr(STDIN_FILENO, TCSANOW, &newt);
        break;
    }
}
#endif
Last edited on
you are saying `if the parameter is true, do nothing', you are setting the same state that you saved.
So if you don't have echo before, you wouldn't after.

newt.c_lflag |= ECHO; //setting echo
Tnx, now i've managed to turn it off and on but i am having another problem :

After i restore echo, when i type something and press backspace, it's showing some weird characters like a squre w/ tiny numbers inside it or something, and so on, blah, blah
like :


here is the code :
1
2
3
4
5
6
7
8
9
10
11
12
void
echo( bool status )
{
    termios termios_;
    tcgetattr( STDIN_FILENO, &termios_ );

    tcflag_t mode = status ? ( mode | ECHO ) : ( mode & ~(ECHO) );
    
    termios_.c_lflag = mode;

    tcsetattr( STDIN_FILENO, TCSANOW, &termios_ );
}
you may want to initialize `mode' before using it.
1
2
3
4
5
6
7
8
9
void echo( bool status )
{
    termios term;
    tcgetattr( STDIN_FILENO, &term );
    
    status ? term.c_lflag &= ~ECHO : term.c_lflag |= ECHO; // <=== ??
    
    tcsetattr( STDIN_FILENO, TCSANOW, &term );
}


It's still not working
provide a testcase
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>

void echo( bool status ) //maybe noecho would be more appropriate
{
    termios term;
    tcgetattr( STDIN_FILENO, &term );
    
    status ? term.c_lflag &= ~ECHO : term.c_lflag |= ECHO; // <=== ??
    
    tcsetattr( STDIN_FILENO, TCSANOW, &term );
}

int main(){
	std::string line;
	bool status=false;
	while( std::cout<<status<<' ' and std::cin>>line ) {
		std::cout<<line<<'\n';
		status=not status;
		echo(status);
	}
}
works on my end
Oh, i see, i was actually thinking the opposite way

here is my final code
1
2
3
4
5
6
7
8
9
10
11
enum Echo_status { OFF = 0, ON =1 };
/* ... */
void echo( Echo_status echo_status )
{
    termios term;
    tcgetattr( STDIN_FILENO, &term );

    echo_status ? term.c_lflag |= ECHO : term.c_lflag &= ~ECHO ;

    tcsetattr( STDIN_FILENO, TCSANOW, &term );
}


Thanks
Last edited on
Topic archived. No new replies allowed.