c - 覆盖文本文件的一部分

标签 c io overriding

文本文件:

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);
}

最佳答案

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

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

关于c - 覆盖文本文件的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37083267/

相关文章:

C# 在文件中搜索字符串并获取字符串的行号

java - 为什么 FilterInputStream 和 FilterOutputStream 在它们的构造函数中有不同的访问修饰符?

c++ - 如何在 C++ 中逐字符输入?

Javadoc 创建 'Specified by' 标题

计算 UNIX 进程时间溢出之前还有多少天

c - 在函数中释放取消引用的堆分配 block

c - matlab c s 函数的数组输出

c - 移动比变量更多的位是 c 中未定义的操作吗?

ios - 如何覆盖包含 block 的objC中的方法?

c++ - 用C++实现自然动态矩阵