写入系统调用 Unix 不会从 Argv 写入所有文本

write system call unix doesn't write all text from argv

本文关键字:文本 Argv 系统调用 Unix      更新时间:2023-10-16

我正在尝试写出用户输入argv[2]的数据。我必须使用 write(( 系统调用 (unix(

例如,我输入"hi there",但"hi th"被写到文件中而不是整个文本中。

#include <iostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>

using namespace std;
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
    int fd, fileWrite;
    char *file = argv[1]; //file to be create
    char *text = argv[2]; //text stored here
    fd = open(file, O_WRONLY | O_APPEND | O_CREAT);
    //write message from command line 
    fileWrite = write(fd, text, sizeof(text));
    fileWrite = write(fd, "n", 1);
    if(fileWrite == -1){
        perror("fileWrite");
    }

    //close file
    close(fd);

return 0;
}`

<string.h> 中使用 strlen(text) 而不是 sizeof(text) 来确定字符串的长度,sizeof(text)将返回指针的大小,这始终相同。