Hi, I'm new to C small question!
Here's the code:
Code:
int main()
{
FILE *in;
int key;
char filename[0];
printf("Enter the filename:");
scanf ("%s", &filename);
if ((in = fopen(filename, "r")) == NULL)
{
puts("Unable to open the file");
return 0;
There is more, but I've got no need to post the rest of it. It does what I want it to, it reads data from a file you specify, and then prints it on the screen. What I'd like to be able to do, is make it only accept a certain length string, since that would teach me more about strings and all, because at this point they are causing me problems!
For instance, in the above code, before I put in "char filename[8];", thinking that if I did that, when Scanf read it, if the user put in more than 8 char's, it wouldn't accept it, you know? I'm really just curious as to how I could handle something like that, if anyone knows what I mean, and why do you have to have a value after "char" in the brackets? What if I don't know just how big I want the maximum to be? Like, "char[10]" or whatever, what if I don't know how big I want that string to be? When I define it, is there anyway to tell the compiler that I don't care what size it ends up being?
I hope I haven't made this too confusing, but I think I'm confused, lol....
thanks in advance guys :)
Re: Hi, I'm new to C small question!
Quote:
Originally posted by Phreedom
Here's the code:
Code:
int main()
{
FILE *in;
int key;
char filename[0];
printf("Enter the filename:");
scanf ("%s", &filename);
if ((in = fopen(filename, "r")) == NULL)
{
puts("Unable to open the file");
return 0;
There is more, but I've got no need to post the rest of it. It does what I want it to, it reads data from a file you specify, and then prints it on the screen.
Wow, it should explode!
First--
char filename[0];
creates a character buffer of 0 bytes, in which you attampt to load whatever is typed into the scanf. You have to define an appropriate size. Use quzah's idea of fgets().
Second--
scanf ("%s", &filename);
As Zainny mentioned, filename is a pointer to the array of charactersa so the & is not needed.