-7

I want to ask the user what is the name of the file to scan, then scan it. This is what I have so far. Im lost. Help? :)

int main(){
    char name[20];

    printf("Enter file name\n");
    scanf("%c", &name);

    FILE * Info;
    Info = fopen("" , "r");

    system("pause");
    return 0;
}
2
  • 1
    system{"pause"); ? typo error? Nov 8, 2014 at 3:53
  • what about Info = fopen(name , "r"); Nov 8, 2014 at 3:56

1 Answer 1

0
#include <stdio.h> 
#include <stdlib.h> 
// You need to include the relevant headers
//  - stdio.h  for printf, scanf etc
//  - stdlib.h for system

int main(void)
{
    char name[20];
    printf("Enter the file name: ");
    scanf("%19s", name);
    // Scan a string (word). Since the array size is 20, scan a 
    // maximum of 19 characters (+1 for the \0 at the end)
    // so that we don't run into a buffer overflow situation

    FILE* info;
    // Not recommended to use capital letters at the start for variables
    info = fopen(name, "r");
    if(info == NULL)
    {
        // Opening the file failed
        printf("Opening %s failed", name);
    }
    else
    {
        // Opening the file was successful

        // Read the file etc

        // Close the opened FILE object
        fclose(info);
    }

    system("pause");
}
5
  • You probably don't want to use a buffer of only 20 bytes to hold a user-supplied filename obtained via a %s that doesn't have a maximum field width.
    – Jason C
    Nov 8, 2014 at 3:58
  • I added 19 in the scanf. What's the problem with a 20 byte array?
    – Spikatrix
    Nov 8, 2014 at 4:02
  • Thank you guys for your input! It keeps saying that it couldnt open the file. Do you know why that could be? Its just a text file in the same folder as the program. Nov 8, 2014 at 4:03
  • @user3047983,Enter filename.txt . Note the .txt
    – Spikatrix
    Nov 8, 2014 at 4:04
  • THat worked! You guys rock Nov 8, 2014 at 4:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.