如何在C中的特定位置插入值?
例如:
const char filenameC[] ="AndModel.c";
FILE * fileC=fopen(filenameC,"r");
int LineNumber=1;
char line[200],search_string[]="similar";
if( fileC)
{
while ( fgets ( line, 200, fileC ) != NULL )
{
if(strstr(line,search_string))
{
fputs ( line, stdout );
printf("%d", LineNumber);
}
LineNumber++;
}
}
FILE * fileW=fopen(filenameC,"w");
fseek(fileW, LineNumber,SEEK_SET);
fputs("hello",fileW);
printf("\n");
return 0;
答案 0 :(得分:0)
好的,这是你的解决方案:
for (int i = number_of_elements -1; i >= desired_position; i--)
{
line[i + 1] = line[i];
}
line[desired_position] = value;
所以对于你的代码,如果我想将数组的元素插入到位置3,并将该值设置为'd',那么我就这样做:
if (fileC)
{
while (fgets (line, 200, fileC) != NULL)
{
if (strstr (line, search_string))
{
for (int i = 200 - 1; i >= 3; i--)
{
line[i+1] = line[i];
}
line[3] = 'd';
printf ("%s", line);
fputs (line, stdout);
printf ("%d", LineNumber);
}
LineNumber++;
}
}