覆盖部分文本文件

时间:2016-05-07 00:32:59

标签: c io override

文字档案:

line_1: abcdefg

将第一个k字符重写为ttttt,以便新文本文件为:

line_1: tttttfg

我使用了fprintf,在打开.txt文件时,我使用了w+标记,但它会删除整个.txt文件而不是仅覆盖第一个bytes_number个字符

我尝试了很多似乎没什么的东西。任何提示都会感激不尽! 提前致谢!

void my_write (char* path, int bytes_number, char* flag, char* data, int sockfd)
{
    FILE* fp;
    char* test;
    int n, i;
    char buffer[BUFFER_SIZE];
    if (bytes_number > 1000 || bytes_number < 0)
    {
        write (sockfd, "Failure", strlen("Failure"));
        return;
    }
    test = data;
    if (strlen(test) < bytes_number)
    {
        write (sockfd, "Failure", strlen("Failure"));
        return;
    }
    if (!strcmp(flag, "override"))
    {
        fp = fopen(path, "w+"); /* Open file with flag 'w' so that we overrun the data */
        if (fp == NULL) { /* File doesn't exist, invalid path*/
            write (sockfd, "Failure", strlen("Failure"));
            return;
        }
        **i = fprintf (fp, "%.*s\n", bytes_number, data);**
        if (i < 0)
            write (sockfd, "Failure", strlen("Failure"));
        else
            write (sockfd, "Write Success", strlen("Write Success"));
    }
    else if (!strcmp(flag, "append"))
    {
        fp = fopen(path, "ab"); /* Open file with flag 'ab' so that we don't override data while writing */
        if (fp == NULL) /* File doesn't exist, invalid path*/
            write (sockfd, "Failure", strlen("Failure"));
            i = fprintf (fp, "%.*s\n", bytes_number, data);
        if (i < 0)
            write (sockfd, "Failure", strlen("Failure"));
        else
            write (sockfd, "Write Success", strlen("Write Success"));
    }
    else {
        write (sockfd, "Failure", strlen("Failure"));
    }
    fclose(fp);
}

1 个答案:

答案 0 :(得分:2)

fopen(path,"w+")打开一个文件进行写入和更新,如果文件已经存在,则先删除该文件。为避免首先删除文件,可以使用fopen(path,"r+")将其打开以进行阅读和更新。

如果目的只是替换指定的字符,则应省略\n格式字符串末尾的fprintf,以便该行显示i = fprintf (fp, "%.*s", bytes_number, data)