cli input在c中出现分段错误Linux文件I/O



我试图编写一个c程序,该程序通过命令行指定文件名,然后通过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,"%dn",numbers[temp]);
}
fclose(nfp);
}

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

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

因为CCD_ 1是5字节长度;纳米\0";并且你附加了空格"one_answers"分配"位置后的内存文件名。您需要预先分配足够的command来容纳具有文件名的nano命令。例如,您可以尝试:

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

最新更新