fprintf 将前 k 个字符写入缓冲区

fprintf to write into buffer the first k chars

我得到了一个文件的路径,我应该修改它,无论是将数据添加到文件中,还是覆盖 file.txt 中的数据。

我也给了一个限制,如果data指向的字符串中有100个字符,并且限制为10,那么fprintf应该只写前10个字符。

fprintf好像没有带这样的参数(limit)。 有人可以建议我解决这个问题的方法吗? 提前致谢!

void my_write (char* path, int bytes_number, char* flag, char* data, int sockfd)
{
    FILE* fp;
    int n, i;
    char buffer[BUFFER_SIZE];
    if (!strcmp(flag, "override"))
    {
        fp = fopen(path, "w+"); /* Open file with flag 'w' to override data */
        if (fp == NULL) /* File doesn't exist, invalid path*/
            write (sockfd, "Failure", strlen("Failure"));
        i = fprintf (fp, "%s\n", data);
        if (i < 0)
            write (sockfd, "Failure", strlen("Failure"));
        else
            write (sockfd, "Write Success", strlen("Write Success"));
    }
    rest of code
}

It seems fprintf doesn't take such a parameter (limit).

您可以在 printf 中指定字符串的宽度和精度。精度,在一段时间后给出,如果字符串更长则截断它:

printf("%.5s\n", data);

最多打印data的五个字符。

您可以通过指定星号来使宽度和精度可变。然后 printf 在 actzual(字符串)参数之前期望每个星的整数参数:

printf("%.*s\n", k, data);

请注意,宽度和精度必须是 int 类型。如有必要,投射参数:

printf("%.*s\n", (int) k, data);      // k is size_t, say

使用 fwrite() 代替 fprintf()

fwrite(buffer, sizeof(char), k, fp);

其中 k 是您的限制参数