1

我试图编写 ac 程序,该程序通过命令行指定文件名,然后通过 system() 调用打开文件上的 nano 编辑器。

在编辑和保存文件后,c 程序通过首先读取文件、对内容进行排序然后写入文件来对文件进行排序。

但我收到分段错误。请帮忙。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argcn,char **args)
{
char *filename=*(args+1);
char *command="nano";
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
system(command);




int numbers[100];
int n=0;
FILE *fp;
fp=fopen(filename,"r+");
while(1>0)
{
  int num;
  int x=fscanf(fp,"%d",&num);
  if(x!=1)
    break;
  else
  {
    numbers[n]=num;
    n+=1;
  }
}
numbers[n]=-1;

int temp;
int temp1;
for(temp=0;temp<(n-1);temp++)
{
  for(temp1=(temp+1);temp1<n;temp1++)
  {
    if(numbers[temp1]<numbers[temp])
    {
      int t=numbers[temp1];
      numbers[temp1]=numbers[temp];
      numbers[temp]=t;
    }



  }

}
fclose(fp);
FILE *nfp;
nfp=fopen(filename,"w");
for(temp=0;temp<n;temp++)
{
  fprintf(nfp,"%d\n",numbers[temp]);
}
fclose(nfp);

}
4

1 回答 1

1

此代码可能导致未定义的行为

char *command="nano";
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);

因为command是 5 字节长度填充了“nano\0”,并且您在“分配”位置之后将空间“”和文件名附加到内存中。您需要预先分配command足够的空间来保存带有文件名的 nano 命令。例如,您可以尝试:

char command[256];
strcat(command,"nano");
strcat(command," ");
strcat(command,filename);
char *txt=".txt";
strcat(command,txt);
于 2020-09-17T18:57:19.287 回答