C Program PLEASE HELP!

This is a discussion on C Program PLEASE HELP! within the C Programming forums, part of the General Programming Boards category; Hi, I'm a newbie C programming student, so please note that my program may look silly and simple to you ...

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    166

    C Program PLEASE HELP!

    Hi, I'm a newbie C programming student, so please note that my program may look silly and simple to you and my question may be stupid.
    Code:
               #include <stdio.h>
    #include <stdlib.h> #include <string.h> #define MAX 81 FILE *fileOpen(char fileName[]); int readFile(); int main (void) { char fileName[MAX] = ""; FILE *inputFile; fileOpen(fileName); readFile(); return 0; } FILE *fileOpen(char fileName[]) //function A { FILE *inputFile; printf("Please enter a file name.\n"); scanf("%s", fileName); if (!(inputFile = fopen("%s", "r"))) { printf("\aCould not open the input file.\n"); exit (100); } // if return (inputFile); } int readFile() //function B { FILE* inputFile; char strng[MAX]; char* pStrng = strng; int len; fgets(strng, sizeof(strng), inputFile); len = strlen(strng); if (strng[len - 1] == '\n'){ strng[len - 1] = '\0'; } while(fgets(strng, sizeof(strng), inputFile)){ fputs(strng, stdin); return 1; } return 0; return; }


    -This code does compile, but my first function is not working correctly. It always returns the error message "Could not open the input file". Even if I type in a valid file... Please let me know how to fix it and any other mistakes that you can catch.
    NOTE: This is by no means a complete program, its just the beginning of what I could get done so far.

    Here is what the second function is supposed to do:
    Create a function that reads one line into a string (assuming the file is already open), the return should be an int or bool (true if a string was successfully read, false if end-of-file). In addition to the string to read into, you may include the physical size of the string as a parameter. When reading into the string, read to the end of line ('\n') using fgets, then remove the '\n' from the end of the string.

    -Let me know if you can't figure out what my first one is supposed to do.

    -THANK YOU FOR YOUR TIME!





  2. #2
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    It's funny that you looked to Yahoo Answers > C language program HELP PLEASE? - Yahoo! Answers before coming to a legitimate programming forum.

    Code:
    if (!(inputFile = fopen("%s", "r")))
    What's this supposed to do? Put fileName instead of the "%s".

    Code:
    FILE *inputFile;
    
    
    fileOpen(fileName);
    What makes you think that inputFile now is open? You're discarding the returned FILE from the fileOpen. Also, learn to fclose().

  3. #3
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,438
    Your indentation is a bit wonky and you managed to bork the syntax highlighting, perhaps by using a non-default font.
    Code:
    if (!(inputFile = fopen("%s", "r")))
    This line is looking for a file that is literally named %s, i.e. a percent sign followed by a lowercase s. Try
    Code:
    ... = fopen(fileName, "r")))
    In main, you need to assign the return value of fileOpen to inputFile, and there's no point in declaring fileName in main, it's only used in fileOpen, so declare it in that function. Also, you can't fputs to stdin, only to stdout or stderr. And that loop in your second function will only execute once if the condition is met, because the return 1; inside ensures the function exits at that point. You should use a if statement or remove the return. You also have a bogus return statement at the bottom of readFile.

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    [QUOTE=memcpy;1090934]It's funny that you looked to Yahoo Answers > C language program HELP PLEASE? - Yahoo! Answers before coming to a legitimate programming forum.

    Hahaha yeah, people tend to not be very helpful and some are just plain rude. Not everyone welcomes beginners.

  5. #5
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Here is the adjustment that I made to the code after reviewing your answers:
    Code:
    #include <stdio.h>#include <stdlib.h>
    #include <string.h>
    
    #include <ctype.h>
    
    #define MAX 81
    
    FILE *fileOpen(char fileName[]);
    int readFile();
    
    int checkCreditCard();
    
    int main (void)
    {
    
    FILE *inputFile;
    char fileName[MAX] = "";
    
    fileOpen(fileName);
    readFile();
    
    return 0;
    }
    
    FILE *fileOpen(char fileName[]) //function A
    {
    FILE *inputFile;
    
    
           printf("Please enter a file name.\n");
           scanf("%s", fileName);
    
    
    
           if (!(inputFile = fopen(fileName, "r")))
           {
            printf("\aCould not open the input file.\n");
            exit (100);
           }
    
    
           return (inputFile);
    
    }
    int readFile() //function B
    {
     FILE* inputFile;
     char strng[MAX];
     char* pStrng = strng;
     int len;
    
           fgets(strng, sizeof(strng), inputFile);
           len = strlen(strng);
           if (strng[len - 1] == '\n'){
                   strng[len - 1] = '\0';
           }
           while(fgets(strng, sizeof(strng), inputFile)){
               fputs(strng, stdin);
                   return 1;
           }
           return 0;
    
    
    return;
    }
    

    -Now when it runs and I type in the file name, it returns "Segmentation fault" and exits. What's the problem now?

  6. #6
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    In main, you need to assign the return value of fileOpen to inputFile, and there's no point in declaring fileName in main, it's only used in fileOpen, so declare it in that function. Also, you can't fputs to stdin, only to stdout or stderr. And that loop in your second function will only execute once if the condition is met, because the return 1; inside ensures the function exits at that point. You should use a if statement or remove the return. You also have a bogus return statement at the bottom of readFile.[/QUOTE]

    -I only understood the first sentence. Could somebody dumb down the rest of it for me? Maybe with an example? I'm having enough of a struggle with this assignment as it is...

  7. #7
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    > In main, you need to assign the return value of fileOpen to inputFile
    Code:
    inputFile = fileOpen(fileName);
    Also, you need to quit passing fileName to the function, as it immediately replaces whatever you pass with the user's input. Pass nothing, and change the prototype accordingly.

  8. #8
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    What do you mean by "passing fileName to the function"? And what is a prototype? (I know this is all sounding stupid, but I really want to understand this and figure it out).
    If you could at least point out where the mistake is (line number or something) that would really help and I might be able to figure it out on my own. Thanks for all the help!

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,438
    Passing it to a function means it's a parameter to that function. It goes inside the parentheses when you call the function. A prototype describes the function (name, return type and parameters) before you actually define it (fill in the body/details of what the function does). It's what you did around lines 7-8 in your original post. It should always match the actual function definition, except it just has a ; at the end, no body.

    It's not exactly a mistake, just something that would "clean up" your code a bit. You never do anything with fileName in main. You never look at the value that the user entered, or pass it to another function. The only thing you do with it is in fileOpen, so declare it inside that function. Like this
    Code:
    int main(void)
    {
        FILE *inputFile;
        // notice I didn't declare fileName in main
    
        inputFile = fileOpen();  // there is nothing in the parentheses
        ...
    }
    
    FILE *fileOpen(void)  // the "void" in there means fileOpen does not take any parameters
    {
        char fileName[MAX] = "";  // declare it inside fileOpen since this is the only place you actually use the variable
        ...
    }
    EDIT: If you're having this much trouble with basic vocab, you really need to grab a good book on the C basics, and start reading. Try C Book Recommendations.

  10. #10
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Quote Originally Posted by anduril462 View Post
    Passing it to a function means it's a parameter to that function. It goes inside the parentheses when you call the function. A prototype describes the function (name, return type and parameters) before you actually define it (fill in the body/details of what the function does). It's what you did around lines 7-8 in your original post. It should always match the actual function definition, except it just has a ; at the end, no body.

    It's not exactly a mistake, just something that would "clean up" your code a bit. You never do anything with fileName in main. You never look at the value that the user entered, or pass it to another function. The only thing you do with it is in fileOpen, so declare it inside that function. Like this
    Code:
    int main(void)
    {
        FILE *inputFile;
        // notice I didn't declare fileName in main
    
        inputFile = fileOpen();  // there is nothing in the parentheses
        ...
    }
    
    FILE *fileOpen(void)  // the "void" in there means fileOpen does not take any parameters
    {
        char fileName[MAX] = "";  // declare it inside fileOpen since this is the only place you actually use the variable
        ...
    }
    EDIT: If you're having this much trouble with basic vocab, you really need to grab a good book on the C basics, and start reading. Try C Book Recommendations.
    -Thank you for the clear explanation! Our teacher calls prototypes datatypes so that was partly why I was confused. Anyway, I corrected the mistakes, but when I run it, it still tells me "Segmentation fault" after I type in the file name...
    -Another detail, I know that you guys want fileOpen to be void, but in our assignment, our teacher said that "string for the prompt will be the only parameters for that function".... are you sure I should keep it void? That's why I had fileName, I thought I was following her instruction.

    I'll post my current code in a sec. Thank you for all your help though. I feel like I'm finally getting somewhere.

  11. #11
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Current code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    #define MAX 81
    
    
    FILE *fileOpen(void);
    int readFile();
    int checkCreditCard();
    
    int main (void)
    {
    
    FILE *inputFile;
    
    
    
    inputFile = fileOpen();
    readFile();
    
    return 0;
    }
    
    FILE * fileOpen(void) //function A
    {https://mail.google.com/mail/images/cleardot.gif
    
    
    
    FILE *inputFile;
    char fileName[MAX] = "";
    
    
    
           printf("Please enter a file name.\n");
           scanf("%s", fileName);
    
    
           if (!(inputFile = fopen(fileName, "r")))
           {
            printf("\aCould not open the input file.\n");
            exit (100);
           }
    
           return (inputFile);
    
    }
    int readFile() //function B
    {
     FILE* inputFile;
     char strng[MAX];
     char* pStrng = strng;
     int len;
    
           fgets(strng, sizeof(strng), inputFile);
           len = strlen(strng);
           if (strng[len - 1] == '\n'){
                   strng[len - 1] = '\0';
           }
           while(fgets(strng, sizeof(strng), inputFile)){
               fputs(strng, stdin);
                   return 1;
           }
           return 0;
    
    
    return;
    }
    

  12. #12
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Closer, now get rid of the extra return statement (second to last line). And get rid of the unused variable pStrng.

    Now, use what you just learned about passing to tell me why readFile() won't work. (hint: the file isn't passed)

    And, you need to learn how to fclose() when you're done using files.

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,438
    If the assignment says pass fileName to fileOpen, then follow the instructions. The seg fault is probably in readFile. A local variable in readFile with the same name as a variable in main is a totally different variable. You're trying to read from the local file pointer, which points to nothing in particular, and thus accessing invalid memory (the cause of a seg fault). You need to pass in the file pointer (inputFile) to readFile and remove the local variable of the same name.

  14. #14
    Registered User
    Join Date
    Jan 2012
    Posts
    166
    Ok memcpy, I think I got it! Here is what I have now:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    
    #define MAX 81
    
    FILE *fileOpen(void);
    
    int readFile(FILE* inputFile);
    int checkCreditCard();
    
    int main (void)
    {
    
    FILE *inputFile;
    
    
    inputFile = fileOpen();
    
    readFile(inputFile);
    
    return 0;
    }
    
    FILE * fileOpen(void) //function A
    {
    FILE *inputFile;
    char fileName[MAX] = "";
    
           printf("Please enter a file name.\n");
           scanf("%s", fileName);
    
    
           if (!(inputFile = fopen(fileName, "r")))
           {
            printf("\aCould not open the input file.\n");
            exit (100);
           }
    
           return (inputFile);
    
    }
    
    int readFile(FILE* inputFile) //function B
    {
    
     char strng[MAX];
     int len;
    
           fgets(strng, sizeof(strng), inputFile);
           len = strlen(strng);
           if (strng[len - 1] == '\n'){
                   strng[len - 1] = '\0';
           }
           while(fgets(strng, sizeof(strng), inputFile)){
               fputs(strng, stdin);
                   return 1;
           }
           return 0;
    
    
    
    }
    

  15. #15
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,438
    Much better. Change fileOpen back to the way it was, where you passed in fileName. Sorry we confused you, I didn't realize your assignment/teacher stated it had to take that parameter. The other problems are in readFile:
    Code:
        while(fgets(strng, sizeof(strng), inputFile)){
            fputs(strng, stdin);
            return 1;
        }
    That is an input file, you can't put (fputs) to stdin. You have to fputs to stdout, so it will show up on the screen.
    That line will cause you to only read one line from the file and echo it back. If that is what you want, change the while to an equivalent if statement. If you want it to read the whole file, remove that line.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help converting array program to link list program
    By hsmith1976 in forum C++ Programming
    Replies: 0
    Last Post: 02-14-2010, 08:50 PM
  2. Replies: 1
    Last Post: 03-03-2009, 03:47 PM
  3. Replies: 5
    Last Post: 08-16-2007, 11:43 PM
  4. Replies: 18
    Last Post: 11-13-2006, 12:11 PM
  5. How To Make The Program Installed In Program Files Folder?
    By javacvb in forum Windows Programming
    Replies: 4
    Last Post: 11-05-2003, 04:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21