-
Why doesn't it work?
I tried:
- to input data (some full names-string) into an array pointer then write these names into a file >> ok
- to delete all data in the array (change all string to '\0') >> ok
The problem is that when I want to restore the data of the array by copying from file (fgets function) something go wrong. Everything printed is just some smiling stupid faces..... Help me check this, pliz
Code:
#include<stdio.h>
#include<conio.h>
int input_n(void);
void input_s(int n,char *str[]);
void clear_enter(int n,char str[]);
int main(void)
{
int n;
int i;
char name[20];
char *string[20];
FILE *fp;
n=input_n();
input_s(n,string);
for(i=0;i<n;i++)
string[i]=(char*)malloc(60);
printf("Store the names in a file named:\n");
fflush(stdin);
gets(name);
//Store all names in a file:
if((fp=fopen(name,"w"))== NULL)
{
printf("Error opening\n");
exit(1);
}
for(i=0;i<n;i++)
fprintf(fp,"%s\n",string[i]);
if(fclose(fp)!=0)
{
printf("Error closing\n");
exit(1);
}
//Delete all data in the array:
printf("After clearing the array\n");
for(i=0;i<n;i++)
{
fflush(stdin);
strcpy(string[i],"\0");
printf("%s\n",string[i]);
}
//Restore the name list from file:
printf("Restore the name list from file. The list is: \n");
if((fp=fopen(name,"r"))==NULL)
{
printf("error opening\n");
exit(1);
}
for(i=0;i<n;i++)
{
fflush(stdin);
fgets(string[i],80,fp);
clear_enter(n,string[i]);
printf("%s\n ",string[i]);
}
if(fclose(fp)!=0)
{
printf("error closing\n");
exit(1);
}
getch();
return 0;
}
int input_n(void)
{
int num;
printf("How many names(full names)?\n");
scanf("%d",&num);
return num;
}
void input_s(int n,char *str[])
{
int i;
char tmp[20];
printf("Enter full names\n");
for(i=0;i<n;i++)
{
printf("\nName #%d: ",i+1);
fflush(stdin);
scanf("%s",&tmp);
str[i]=tmp;
}
}
void clear_enter(int n,char str[])
{
int i;
i=0;
while((str[i]!='\n')&&(str[i]!='\0'))
i++;
str[i]='\0';
}
-
Perhaps start by reading the FAQ, and stop using fflush(stdin) and gets()
-
fflush(stdin) : BAD!
gets() : BAD!
Reading into an array without checking to make sure you've not overrun its boundaries : BAD!
Fix those things first.
-
gets is an unsafe function and does not do its own error checking. Meaning that if you if you have to much data for the space you have set aside for it gets will just keep the ball rolling and ignore the bounds of the size of the space you have set aside.
Please correct if I am wrong.
-
Yes, that's right, and that is exactly why you should never use it.