几天前我已经发布了关于我的数组程序的问题。嗯,它基本上是一个程序,让用户生成一个数组,在特定槽中保存特定数字,读取数组或读取特定槽值。现在我正在弄清楚,如何让用户将当前数组保存为文件。
这就是我得到的
void safeFile(){
FILE *f = fopen("list.txt", "a+");
putc(f , list);
fclose(f);
printf("File saved");
start();
}
问题出在哪里?
每次我调用函数 safeFile() 时,我的程序都会崩溃。
我玩了一下,用的是 fputs 而不是 putc,程序不会再崩溃,文件已创建,但它仍然是空白的
void safeFile(){
FILE *f = fopen("list.txt", "r+");
fputs(f , list);
fclose(f);
printf("File saved");
start();
}
这是我当前的完整代码
非常感谢您的建议,我是新手
#include <stdio.h>
#include <stdlib.h>
int list[30];
int x = 0;
int i = 0; // variable used by for-Loop in setList
int j = 0; // variable used by for-Loop in getList
int input;
int option; //start Value
int gvinput; //getValue input
void start();
void getList();
int main()
{
start();
return 0;
}
void setList(int sizeOfList)
{
for (i = x; i <= sizeOfList; i++)
{
list[i] = i;
}
}
void getList(){
for(j = x; j < i ; j++ )
{
printf("At %d we got the value %d \n",j,list[j]);
}
}
void startList()
{
fflush(stdin);
printf("Please enter number between 0 and 30\n ");
scanf("%d",&input);
if(input > 30 || input == 0)
{
printf("The Number is not between 0 and 30\n");
startList();
}
setList(input);
getList();
fflush(stdin);
start();
}
void setValues(int l[])
{
fflush(stdin);
int v;
int loc;
printf("please enter what value you want to safe\n");
scanf("%d",&v);
fflush(stdin);
printf("Where do you want to save it?\n");
scanf("%d",&loc);
l[loc] = v;
printf("we got at slot %d the value %d\n\n",loc,l[loc]);
start();
}
void getValues(int getArray[]){
fflush(stdin);
printf("which slot do you want to read?\n");
scanf("%d",&gvinput);
fflush(stdin);
printf("The value is: %d \n\n",getArray[gvinput]);
start();
}
void safeFile(){
FILE *f = fopen("list.txt", "r+");
fputs(f , list);
fclose(f);
printf("File saved");
start();
}
void start(){
fflush(stdin);
printf("\n");
printf("[L] = generate Slots\n");
printf("[S] = set a Value at specific slot\n");
printf("[G] = get a Value from a specific slot\n");
printf("[F] = safe File");
printf("[X] = exit\n");
option=getchar();
if(option == 'L' || option == 'l'){
startList();
}
if(option == 'S' ||option == 's'){
setValues(list);
}
if (option =='G' ||option == 'g'){
getValues(list);
}
if (option == 'X' || option == 'x'){
printf("Thank you");
}
if (option == 'f' || option == 'F'){
safeFile();
}
最佳答案
int putc( int ch, std::FILE* stream );
putc
写入一个 char
,然后将一个 int
数组传递给它。 fputs
也是如此,它写入一个以 null 结尾的字符串。您确实必须编写一些代码,将数据结构序列化为要写入文件的字节序列。
在您的情况下,由于您想要保存 int
列表,因此您可以使用循环来完成此操作,例如,循环遍历数组并将每个项目写入文件。您还需要一个写入 int
的函数(putc
在这里不太好,因为它写入 char
)。看看printf
,如果您想坚持使用 C 风格 IO,则使用 streams .
关于c - 将数组保存到文件不起作用,程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21934600/