Question

I am writing a program that concatenates a line input from standard-input with a seperate file, and writes the combined text to an output file. For some reason when I type a full line of text into standard input, only the first word before whitespace is being written. What's wrong with my code?

Accepting from std-in and writing:

// check for stdinput flag
if(strcmp(argv[1], "-") == 0) // use standard-in for input file 1
        {
            printf("Type your text and then hit enter: ");
            p = fgets(userInput, sizeof(userInput), stdin);
            if (write(output_file, userInput, sizeof(p)) < 0)  // write stdin to output file
            {         
                perror(argv[4]);
                close(output_file);
                exit(1);
            }
        }

Further along in the program... writing the second file to output:

    else // open file2 and assign to file-handler, then output to file
    {
        if((input_file2 = open(argv[2], O_RDONLY)) < 0)
        {
            perror(argv[2]);
            close(output_file); // close the opened output file handler
            exit(1);
        }

        while((n = read(input_file2, buffer, sizeof(buffer))) > 0)
        {
            if((write(output_file, buffer, n)) < 0)
            {
                perror(argv[3]);
                close(input_file2);
                close(output_file);
                exit(1);
            }
        }
        close(input_file2);
    }

command line and output:

server1{user25}35: program - file2 outputfile

Type your text and then hit enter: THIS IS MY TEXT FROM STDIN

server1{user25}36: cat outputfile
THISthis is the text in file2

server1{user25}37: 
Was it helpful?

Solution

In your first fragment, you output sizeof(p) characters which is sizeof(char*) (which on a 64-bit system would be 8 bytes). You need to change this to at least strlen(p) (obviously, after checking for an error and NULL return value).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top