Printf prints old buffer - C - c

I'm creating a server/client. The clent sends a message to the server, which stores it into a file. Than the client can read this message.
So, I'm using only the following functions (plus the bind etc): fgets, read (both for read from socket and file) write (to write on files/socket). And printf to print.
The strange thing is that when I call a printf, it happens that it prints an old text. So, for example if I decided to delete all the message, I'll receive from the server a string like "file deleted". Then in the following action, when there's a printf it happens that it prints the desider content plus a part of the previous pessage, like "file dele". How is this possible? What should I check in my code? I'd get things right without using things like fflush(stdout);.

You should check for proper '\0' termination.

Related

Trouble with Scilab "print" instruction

Trying to debug a program in Scilab, I inserted a couple
of "print" instructions to track what is going on.
At first, I used the %io(2) output "file" which, according
to the Help, stands for the console. Nothing happened.
Then I used an actual filename:
print("C:\Leszek\Xprmnt\scl\Ovsjanko\K3ScilabLog.txt", "START! \n \n \n \n GOING \n")
which does print to that file, but when the dust has settled
and I want to inspect the file what I find inside is just the last
message (just before the program crashed), even though there should
have been others before it, including the "START" etc in the quote above.
Apparently, every print command reopens the file for writing as a clean slate,
overwriting whatever was in it before. Looking into Help and online docs
I didn't find any options or parameters that I could use to change this.
What I want is, obviously, the output from all my print commands since the
beginning of the program, either on the console or in a text file.
TIA.
Just use disp("some text") or mprintf("format",var1,...,varn), both will display on the console. If you need to write in a file use fd = mopen("file.txt") then mfprint(fd,"format",var1,...,varn).

Execute shell command from C environment and redirect output

I have seen there are some questions about this topic, but none of the answers satisfied me. Here is the problem: I need to write two sockets (client and server), with the client having to send to the server an awk program with some lines of input. No problem in sending strings back and forth between the sockets. Supposing I have stored the program in a string command and the string I should pass to it in input, I have tried this:
execl("/usr/bin/awk", command, input, (char *)0);
And this works, the awk program runs and it writes on the server's stdout and stderr. Thing is, if there are lines with errors, I need to send these back to the client, which is pretty impossible since execl doesn't give me the chance to store its output in arrays. So, does anybody know a way to do this without using system and popen?

python socket difference noted on shell and code in file

I'm trying to build a python client to interact with my C server. Here's the code for the client:
import socket
s = socket.socket()
s.connect(("127.0.0.1", 12209))
print "preparing to send"
s.send("2")
s.send("mmm2.com")
s.send("mypwd")
s.send("5120")
print "Sent data"
root = s.recv(256)
print root
When I run this code on the interactive shell (the GUI IDLE) of course line by line, everything runs very fine. But when i save this code in a file and try to run it, it hangs and stops responding according to windows, what's it that I'm just not doing?
If you type it line by line, the sent strings are likely received by the server one after another in separate recv() calls.
When you execute it in a script, all the send() calls run immediately after each other without delay and the server will probably receive all the data in one bulk in a single recv() call. So the server will see "2mmm2.commypwd5120", and maybe not handle that correctly. It might wait for more input from the client.
You will need some explicit separation between the values, for example newline characters, so that the server can parse the received data correctly.

Write an entire program to a file in C

I'm quite new to C programming, but I'm starting to get the hang of it.
For a school assignment, I have written a code in C to play Blackjack.
One of the requirements for the assignment, is that is has to have an option that saves the entire output (everything that's shown in cmd when the program is build and run).
I can't find how to do this anywhere.
Is there a way to write the entire output into a file?
Thanks in advance!
There are 3 ways to achieve what you want.
Use a file. This is the way I recommend. You will need the functions fopen to open a file and enter link description here to print the data in the file. I suggest you read the documentation of the functions in the links and look at the examples.
Redirect stdout to a file using freopen. This basically puts everything that you see now in the console in a file, by adding just one line.
Redirect the output of the program in a file. This is more a shell thing than a C programming technique, but I think it is worth mentioning. In an *NIX environment, the command ./a.out > file.txt will redirect the output of a.out to a file called file.txt in a similar manner freopen does.
You can pipe the stdout and stderr to a file when you build and run. For example, on Linux using the bash shell you can do try this (where the "build_script" is what you use to build and the "a.exe" is the program name):
$ ./build_script >& build_out.txt
$ ./a.exe >& run_out.txt &
The ">&" tells bash to pipe both stdout and stderr to the file. The final "&" in the second line tells bash to run the program in the background. It's hard to tell if this answer will suit your purposes since it's not clear exactly how the game is played from what you have posted. E.g., if you need to use stdin/stdout to play the game then maybe piping the "a.exe" stdout to a file might not work...
I'm assuming simple output redirection is not an option:
$ app > file.txt
Probably, you are using printf to print data to console. Instead of printf, you can use fprintf. fprintf can write data to an arbitrary file, just like printf does to the standard output (which is also a file), in this case the console.
You must first open the file where you will write the output. The command fopen will do this for you:
// this will open or create the file as text to write data.
FILE *f = fopen("my-file.txt", "w");
With the f variable (which you should check for NULL in case of error), you can pass it to fprintf to write data:
fprintf(f, "my super string: %s", string);
Note that despite the first argument being a FILE*, everything else behaves like printf. Actually you can think of printf as a wrapper where the first argument of the fprintf is always stdout.
Do not forget to close your file after you write data!
fclose(f);
This can be done once, after all the data is written to file.
Check the man pages for more info about these commands.
There are more complex (not that much actually) ways of accomplishing this, like using freopen, but I'm leaving this out of the answer. If you need more, update your answer.
EDIT
In your comment, you said you must save or not the output to a file at the end of the program. Well, the file management stuff above you still be usefull. The changes are the following:
You must store the output somewhere in order to decide whether to write to a file or not at the end of the program. Probably you are doing some data formatting with printf. You will have to change your calls from printf to snprintf. This command will write your data to a string, just as printf does prior to output it to the stdout, but it will skip the print-to-output- part.
Then, store the buffer at a list of strings and at the end of the program you write this list to the file or not.
This has some complications: you need a list of strings (a dynamically allocated array of arrays will be enough, actually); how big must your buffer be?
snprintf will return the size required to print the passed data to the buffer, no matter if the buffer is larger or smaller then the given one. But, if it is smaller, you will have to increase its size (reallocating it) and call again snprintf:
char *buffer = malloc(sizeof(char) * 41); // 40 chars + \0!
int size;
if ( size = snprintf(buffer, 41, "your format here", args) > 40 ) {
buffer = realloc(buffer, sizeof(char) * (size + 1));
snprintf(buffer, size + 1, "your format here", args);
}
// now your buffer have the correct data!
// print it to stdout!
puts(buffer);
// store it at the string list.
// execise!
Is left as an exercise wrapping this piece of code in a command to avoid repeat it everywhere you print anything. Also, it is an exercise to create the list of strings.
When you decide to write data to file, instead of use fprintf you can use fputs, as data is already formatted.
I don't know if there is an easier way. I think not.

simultanous read and write (stdin, stdout) in C

I'm trying to write a chat client and server and the client should be able to print the messeges from the server while also writing something on the console.
So I created a pthread that should read the user input and the main thread prints the messeges from the server. But when I type something and while typing a messege is received, the text I was typing is pushed up on the console. How can i fix that?
for example:
I'm typing "abcdef" and then when I get a messege from the server (but didn't finish typing yet) it will look like this:
abcdef[Chatuser1]:Hello
Use synchronization technique like semaphore or mutex to synchronize input and output in your multi threaded program
I would really recommend doing something like this in a GUI with two seperate edit box elements and not in a console.
If you still want to do it in a console, you will need to do direct console buffer modification.
Every time a new output message arrives, the current input message has to be backed up so you can savely write to the console then do some custom scrolling and add the input message back again. Thread syncronisation is needed to prevent mixing of input and output in the buffer.
I think you also would not get around custom key handling, because otherwise you have no access to partialy typed input.

Resources