0

I'm doing program and in this program i have two processes, server and client. Server have to read string from input and then write into FIFO file. Client have to read strings from FIFO file and then wrote into .txt file. This are only function responsible for server and client. File FIFO and fork'ing is doing in main function.

void server(void)
{
    FILE *fp1, *fp2;
    char string[100];

    while(1)
    {
        fp1 = fopen("FIFO1", "w");
        fprintf(stdout, "Type string: ");
        scanf("%s", string);
        fputs(string, fp1);
        fclose(fp1);

        sleep(1);
    }
}
void client(void)
{
    FILE *fp,*fp1;
    char string[100];
    while(1)
    {
        fp = fopen("FIFO1", "r");
        fgets(string, 100, fp);
        fclose(fp);
        fp1 = fopen("file.txt", "a");
        fprintf(fp1,"%d_file: I get: %s\n", getpid(), string);
        fclose(fp1);    
    }
}

And my problem is when i type a string like "stack overflow", when i have two word, in my file.txt i get to lines:

8965_file: I get: stack
8965_file: I get: overflow

Is there any way to write this in one line ? Like this:

8965_file: I get: stack overflow
Piter _OS
  • 105
  • 2
  • 11

2 Answers2

2

It's because of scanf() which stops reading when a white space occurs for the "%s" specifier, change it to "%99[^\n]" or use fgets() instead but keep in mind that fgets() will read the '\n' and fputs() will add one so you might end up with more lines than you want.

Hint: For an array use fgets(string, sizeof(string), fp); to make your code easier to maintain.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • `puts()` adds the newline, `fputs()` does not. – John Hascall Jan 05 '16 at 00:45
  • I change "%s" to "%99[^\n]" and i got weird behavior because program write on screen multiple times, that i can't count, "Type string:" and in file it write multiple times '8965_file: I get: stack overflow' and then ends :( any ideas why ? – Piter _OS Jan 05 '16 at 00:46
-2

You can use gets(string) to get more than one word instead of using scanf().

Reference Link : www.keizerkong.com/c/c_string.html

Sanjuktha
  • 1,065
  • 3
  • 13
  • 26
  • 1
    gets is dangerous because you do not specify the length of your buffer, so it can be overrun with too much input -- use `fgets()` instead – John Hascall Jan 05 '16 at 02:46
  • It works :) I have warning that gets function is dangerous and should not be used. Here is why: http://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used – Piter _OS Jan 05 '16 at 02:46
  • @John Hascall thanks :) I changed scanf in server to fgets(string, sizeof(string), stdin); – Piter _OS Jan 05 '16 at 02:49