【发布时间】:2015-08-23 07:02:32
【问题描述】:
我正在尝试创建一个函数,该函数将!! 附加到文本文件从(包含)到(不包含)每一行的末尾。在我遇到了几次并发症后,我实际上成功了。但不完全。
int incldue_auto (char *script, unsigned int offsetLine, unsigned int endLine)
{
size_t fileSize;
size_t content = (endLine - offsetLine) * 3; // New characters
char *buffer;
FILE* fp;
if((fp = fopen(script, "r")) == NULL) //return(1);
if(fseek(fp, 0l, SEEK_END) != 0) //return(2);
if((fileSize = ftell(fp)) == (-1l)) //return(3);
if(fseek(fp, 0l, SEEK_SET) != 0) //return(2);
if((buffer = calloc(fileSize + content, sizeof(char))) == NULL) //return(4);
if(fread(buffer, sizeof(char), fileSize, fp) != fileSize) //return(5);
if(fclose(fp) == EOF) //return(6);
{
int i, i2;
int lines = 0, ln = 0;
for(i = 0; i < fileSize; i++)
{
if(ln >= (endLine - offsetLine) || i[buffer] == '\0') break;
if(i[buffer] == '\n')
{
lines++;
if(lines >= offsetLine && lines < endLine)
{
char* p = (buffer + i); // \n
//if(*(p - 1) == '\n') continue;
memmove(p + 3,
p,
strlen(p)); // <-- Problematic line (I think)
memcpy(p, " !!", 3);
i += 3;
ln++;
}
}
}
fp = fopen(script, "w");
fwrite(buffer, fileSize + content, sizeof(char), fp);
fclose(fp);
}
free(buffer);
return 0;
}
它相对工作得很好,除了它没有附加到最后一行。它最后用空格(可能是NULL)填充文本文件。
我认为这是因为我也在移动 enzero-ed 附加区域content:
memmove(p + 3,
p,
strlen(p)); // <-- Problematic line (I think)
【问题讨论】:
-
大概,这意味着您的旧问题Appending characters at the end of a specific range of lines in a file 不再相关。请删除它。
-
我建议您对文件使用二进制模式:
fopen(..., "...b") -
@pmg 在二进制模式下根本不起作用(数据转换为无符号字符)