0

たとえば、入力ファイルの内容を次のように出力ファイルに書き込むことができます。

char buffer[1024]; // character buffer
char userInput[1024]; // for user input
char *p;
char *q;
int n;
int input_file1; // file descriptor for file 1
int input_file2; // file descriptor for file 2
int output_file; // file descriptor for output_file

    while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
    {
    progress("entered first while loop");
        if((write(output_file, buffer, n)) < 0)
        {
            progress("couldn't write to output within while loop 1");
            perror(argv[3]);
            close(input_file1);
            close(input_file2);
            close(output_file);
            exit(1);
        }
    }

ユーザー入力もあります。

printf("\nEnter text then hit enter: ");
q = fgets(userInput, sizeof(userInput), stdin);

write(); を使用して、ユーザー入力を同じ出力ファイルに追加したいと考えています。

これどうやってするの?

----- 更新 ---- で動作します

if(strcmp(argv[1], "-") == 0) // use standard-in for input file 1
    {
        progress("file 1 detected as \"-\": using std input");
        p = fgets(userInput, sizeof(userInput), stdin);
        if (write(output_file, userInput, sizeof(p)) < 0) {
            progress("write from stdin to output file failed");
            perror(argv[4]);
            exit(1);
        }
        progress("wrote from stdin to output file");
    }
4

4 に答える 4

1

同じものを作るだけです。ただし、最初のうちはファイルを閉じる必要はありません。

write()ユーザーから入力を取得し(stdin)、関数を使用してファイルに書き込みます

q = fgets(userInput, sizeof(userInput), stdin);
write(output_file, userInput, strlen(userInput));
close(output_file);
于 2013-10-30T08:35:40.320 に答える
0

output_file既にを書き込み用に開いている (場合によっては書き込みも行っている)と仮定します。

#define MAX 120
char buffer[MAX];
int len = sprintf(buffer, "Whatever you want to print in %d characters.\n", MAX);
if (write(output_file, buffer, len) < 0) {
   perror("Cannot write to file.");
   exit(1);
}
于 2013-10-30T08:35:55.590 に答える