c - 未处理的异常,将信息写入文件C语言

标签 c exception printf unhandled

这就是我想做的,

我有一个包含信息的文件。我正在尝试重写它,以便在每一行之前,都会出现行号。

我想到的基本想法是这样的:

while i haven't reached the end of the file:
save the first line of the file (100 characters or until null is reached) in str
go back to the file, and write "line number" and then the info in str.
now str takes the next 100 chars...rinse and repeat.

实际代码:

void add_line_number(FILE* f1)
{
    char str[100];
    int i=1;
    fseek(f1,0,SEEK_SET);
    do
    {
        fgets(str,100,f1);
        fprintf(f1,"%d %s",i,str);
        i++;
        f1+=strlen(str);
    }while(strlen(str));
}

收到错误:论文 4.exe 中 0x77e78dc9 处出现未处理的异常:0xC0000005:访问冲突写入位置 0xfffff204。

最佳答案

一般来说,您无法让它正常工作。在行的开头添加行号,然后将其写回到文件中,将导致第一行的末尾覆盖第二行的开头。您需要将修改后的行写入单独的文件,然后在完成后覆盖原始文件。或者,将文件的所有行存储在内存中,然后在第二遍中覆盖该文件,但这对于大文件来说会出现问题。

关于c - 未处理的异常,将信息写入文件C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16530015/

相关文章:

c - 如何破解 elf 文件以调用其他 function() 而不是 main?

c - C 代码中的内存问题或 Arduino 限制?

c - 在哪里解锁pthread中的互斥量?

c# - 捕获和识别 HttpRequestException "The remote name could not be resolved: ' www.example.com'"的正确方法是什么?

c - vsprintf 缓冲区的动态内存分配

c - 如何从 C 命令行读取星号 ( * ) 作为参数

Java套接字 - 简单的程序不起作用

java - Mockito 异常 : Missing method invocation while trying to test an if conditon

c - 十六进制 printf C 编程

c - 如何使用 printf() 实现可变字段宽度?