c++ - 写入系统调用 unix 不会写入来自 argv 的所有文本

标签 c++

<分区>

我正在尝试写出用户输入到 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;
}`

最佳答案

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

关于c++ - 写入系统调用 unix 不会写入来自 argv 的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394196/

相关文章:

java - 等效于 C++ long long 的 BigInteger 值

c++ - 如何从 dll 正确返回 std::list

c++ - 一种使用boost和c++列出目录和子目录下所有文件的方法

java - 在 Android 上用 Java 或 C/C++ 解码 Airplay 数据包

c++ - 检查当前线程是否为主线程

c++ - 返回值寄存器和析构函数调用顺序

c++ - T4 模板——适合生成 C++ 代码吗?

c++ - Qt : CONFIG += C++11, 但 -std=c++0x

c++ - 我在哪里可以找到所有 C++ 十进制类型指示器?

c++ - 在此示例中,赋值运算符重载决策如何工作?结果出乎我的意料