我目前正在尝试解决一个问题。我想在一个txt文件中添加几行。比方说20行。然后我检查添加了多少行,当我达到20行时,再次从文件的开头开始添加行。表示要重置文件指针并从第一行开始覆盖。
我使用echo命令在文件中添加行,它总是不断地追加文件。但它不会重置文件指针。
我也尝试过以附加模式打开文件,但它不允许在文件开头重置文件指针。
W+和r+模式对我也没有用。有人能给我推荐解决方案吗?我主要使用C语言或shell脚本。
您是否尝试将fseek与SEEK_SET一起使用?https://www.tutorialspoint.com/c_standard_library/c_function_fseek.html
shell脚本:如果使用linux,请使用命令sed
。您可以删除或替换第一行、第二行、第四行以及其他行。动力十足!
使用命令wc -l
显示您有多少行。
c代码使用您想要的fseek
。
找到你最喜欢的解决方案吧。
我的代码显示它可以与fseek一起使用
#include <stdio.h>
void writeToFile(FILE*, char*);
int main(void)
{
/* Mode: w or w+ //Content of file will be gone! */
long pos;
FILE* fhwrite = fopen("Lines.txt","w");
writeToFile(fhwrite,"I'M 1.st linen");
writeToFile(fhwrite,"I'M 2.nd linen");
writeToFile(fhwrite,"I'M 3.rd linen");
/* Position of line 4 */
pos = ftell(fhwrite);
writeToFile(fhwrite,"I'M 4.th linen");
writeToFile(fhwrite,"I'M 5.th linen");
fseek(fhwrite,pos,SEEK_SET);
/*
Windows: rn | 2 Bytes more for replace
Linux: n | 1 Byte more for replace
*/
writeToFile(fhwrite,"REWRITE LINE 4n");
fclose(fhwrite);
}
void writeToFile(FILE* fh, char* putTextToFile)
{
printf("Current position: %ldn", ftell(fh));
fprintf(fh, "%s", putTextToFile);
}
结论|结果:
您必须读取整个文件,替换特定行。所做的所有更改都可以将其写回文件中。
我认为bash脚本对您的操作来说要容易得多(IF LINUX(^^。