gpt4 book ai didi

在 c 中创建文件时中止 : 6 error

转载 作者:行者123 更新时间:2023-11-30 15:10:07 25 4
gpt4 key购买 nike

循环只经过0-9,输出是这样的。我收到的错误是 abort 6 ,我不确定这是什么意思

   1.txt 38 
2.txt 5
3.txt 6
4.txt 24
5.txt 17
6.txt 12
7.txt 34
8.txt 30
9.txt 6
Abort trap: 6

下面的代码每次运行都会创建相同的随机数,我怎样才能使其更加随机

void save(char *, int );
void create(char *, int );
void close();
FILE * list;
FILE * file;
int main(void)
{
char ext[4] = ".txt";
static const int MIN = 1 ;
static const int MAX = 40 ;
int rdm , fsize;


list = fopen("filelist.txt","w");
char str[2];

//char str3[6];
list = fopen("filelist.txt", "a+");


for(int i = 0 ; i < 10 ; i ++ )
{
sprintf(str,"%d",i+1);

char * str3 = (char *) calloc(1,1 + strlen(str)+ strlen(ext) );
//file = fopen(str3,"r");
strcat(str3,str);
strcat(str3, ext);
// printf("%s \n",ext);
//strcat(str3, ext);
rdm = (rand()%(MAX-MIN)+MIN);
printf("%s %i \n",str3, rdm);
save(str3 , rdm);
create(str3 , rdm);
// printf("%s \n",ext);

}
close();
}

void save(char * fname , int sz)
{

fprintf(list , "%s %d %d \n" , fname , sz , sz*512 );

}

void create(char * fname , int sz)
{
file = fopen(fname, "w");
fseek(file, sz*512, SEEK_SET);
fputc('\n', file);
fclose(file);

}

void close()
{
fclose(list);

}

最佳答案

这里至少有三件事:

首先,你的 main 函数返回 int:

int main()

因此,在成功运行代码的情况下,您应该在最后一行返回 0:

...//all other lines
return 0; //no error

其次,rand()是伪随机随机。它每次根据所使用的随机数种子生成预定的随机数。为了使 rand() 值每次都改变,请考虑将时间作为 srand() 中的随机种子。那么你的随机值就会根据时间而变化。

#include <time.h>
...
srand(time(NULL)); // randomize seed
//do it once before you use rand()

第三,正如评论所述,您的字符数组大小似乎太小:

char ext[5] = ".txt"; //should be 5, the last one will be \0
...
char str[15]; //should be large enough for your text

关于在 c 中创建文件时中止 : 6 error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com