Thread: C Help

  1. #46
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Yeah, that works...
    Now, remember the fopen returns a FILE*. You need to save this, because this is the stream to the file that you must pass to fgets to read from the file later.
    So usually, you save that FILE* from fopen and check it for NULL. If it's NULL, you usually print an error and abort. Otherwise, you proceed.

  2. #47
    Registered User
    Join Date
    Nov 2007
    Posts
    38
    Alright, thanks

  3. #48
    Registered User
    Join Date
    Nov 2007
    Posts
    38
    Alright looks like I have it working. Only a couple of tweaks I believe need to be done for example. When I run the program it gives me the message: "The file is open" followed by the first line of the file. Where do I put "/n" or some other character to make the first line of the file jump to the next line. In addition, if i wanted to just get rid of "the file is open" message, would I have to then place the while loop inside the if statement. Finally, my professor wanted us to be able to take in a list of files and have the program display the first lines for each of the corresponding files. This as far as I know can be done in a loop, does it matter what kind of loop I use, and how would I get that started?

    Code:
    #include <stdio.h>
    
    int main(int argc)
    
        {
    FILE *fp;
    char filename[100];
    char arr[200];
    
    printf("Enter FileName /n");
    
    scanf("&#37;s",filename);
    
    if (fopen(filename, "r")) {
    printf ("The file is open.");
                               }
    else (printf("The file failed to open"));
    
    while (fp=fopen(filename, "r"))
           {
    
    fgets(filename, 200, fp);
    
    fputs(filename,stdout);
           }
    
    }

  4. #49
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Does it actually do what you want?

    To me, it looks like this code
    Code:
    while (fp=fopen(filename, "r"))
           {
    
    fgets(filename, 200, fp);
    
    fputs(filename,stdout);
           }
    Opens a file, then tries to open the file by the name of whatever is the first line in the file it just opened, and do this until it fails [which is probably the first attempt, as most files don't end there name with a newline].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #50
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by CrazyShellsSlam View Post
    Alright looks like I have it working. Only a couple of tweaks I believe need to be done for example. When I run the program it gives me the message: "The file is open" followed by the first line of the file. Where do I put "/n" or some other character to make the first line of the file jump to the next line. In addition, if i wanted to just get rid of "the file is open" message, would I have to then place the while loop inside the if statement. Finally, my professor wanted us to be able to take in a list of files and have the program display the first lines for each of the corresponding files. This as far as I know can be done in a loop, does it matter what kind of loop I use, and how would I get that started?
    I suggest you design a menu first. A while loop will do fine.
    The character for newline is "\n". Just type \n where you want a newline and you'll get it. And work on indentation. It's still horrible twisted and painful to read.
    As for your code... it's still flawed:

    Code:
    #include <stdio.h>
    
    int main(int argc)
    {
    	FILE *fp;
    	char filename[100];
    	char arr[200];
    
    	printf("Enter FileName /n");
    	scanf("%s",filename);
    	if (fopen(filename, "r"))
    	{
    		printf ("The file is open.");
    	}
    	else (printf("The file failed to open"));
    
    	while (fp=fopen(filename, "r"))
    	{
    		fgets(filename, 200, fp);
    		fputs(filename,stdout);
    	}
    
    }
    ...The code is still horrible. Very much so.
    Think for a moment what you're actually doing. It seems to me that you're just trying to make it work. You don't actually know WHAT you're doing.
    There's no sense in writing a program if you don't know what you're doing.
    I have marked bad code with red text. See if you can actually fix it. First think about what you're doing. Let's start from there.

  6. #51
    Registered User
    Join Date
    Nov 2007
    Posts
    38
    I'm a bit confused...
    Are you saying that the code in red is bad code practice? Because if thats the case, then what can I do to improve it?

  7. #52
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    It's not so much that it's bad practice as "It doesn't do what you think it does" - and I think Elysia's point is that your are just trying to make the code compile [and perhaps also do what you want it to do], but you don't actually understand what you are doing. You are just guessing on a different combination, posting it here to get a "fix for the problem". You need to stop messing with the code, and go back reading up on what the functions you are using actually do, and try to understand better what you should do to achieve the functionality you want. I presume you actually want to read all lines of your input file, rather than only the first line, right?

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #53
    Registered User
    Join Date
    Nov 2007
    Posts
    38
    No...the point of the program was to read only the first line of the text file. That was the assignment lol.

  9. #54
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Ok, so you don't need a while-loop then, a simple if would be fine.

    [unless you actually want to open the file indicated by that first line, and the file indicated in that file, etc, etc. In that case you probably want to get the newline at the end stripped off].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #55
    Registered User
    Join Date
    Nov 2007
    Posts
    38
    Well the assignment also wants us to take a list of filenames and print out the first line. So wouldnt u need some kind of loop for that? Because the program asks u for the first file...u supply it....then the second file....u supply it...then the third...u supply it and so forth THEN finally it prints to stdout the first line of all x amount of files.

  11. #56
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by CrazyShellsSlam View Post
    Well the assignment also wants us to take a list of filenames and print out the first line. So wouldnt u need some kind of loop for that? Because the program asks u for the first file...u supply it....then the second file....u supply it...then the third...u supply it and so forth THEN finally it prints to stdout the first line of all x amount of files.
    Yes, but if you want to achieve that, you need to have a loop further out, around the code that asks for the filename, not around the code that opens and reads the file, as that won't repeat "askign for the filename"...

    Is is possible that you could exert enough energy to write proper english words instead of your shortened text-speak. It may be that you are quite used to reading such rubbish, but for me, it's quite hard to read "u" instead of "you" - Yes, I know, it saves two letters. [But I guess is you remove the .... you'd end up with the same amount of typing].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #57
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by matsp View Post
    It's not so much that it's bad practice as "It doesn't do what you think it does" - and I think Elysia's point is that your are just trying to make the code compile [and perhaps also do what you want it to do], but you don't actually understand what you are doing. You are just guessing on a different combination, posting it here to get a "fix for the problem". You need to stop messing with the code, and go back reading up on what the functions you are using actually do, and try to understand better what you should do to achieve the functionality you want. I presume you actually want to read all lines of your input file, rather than only the first line, right?

    --
    Mats
    That is exactly what I'm implying.
    You've pretty much just jumbled around the code without thinking of what you're doing or what the code does. You've also ignored or forgotten that I told that that you're reading into the wrong buffer and that you're specifying wrong buffer size, which adds to the troubles.
    There's no use to keep working with the code if you don't know what you're doing. If you can't understand what you're doing, then go back to basics or ask your teacher, because this is not how you make a program.
    We can help you do your homework or assignment, but if you can't code, then we can't help you.

  13. #58
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Some points that may help you:
    • fopen() returns a FILE* file pointer -- make sure you always save this pointer in a variable.
    • You should only need to call fopen() once. If fopen() fails, you might want to call it again, but only with a different filename, or else it will just fail once more.
    • main() can be one of the following forms (including some variations):
      Code:
      int main()
      int main(void)
      int main(int argc, char **argv)
      int main(int argc, char *argv[])
      Since you're not using command-line parameters, you can get away with one of the first two.
    • You have two strings -- one to hold the filename, the other to hold the first line of the file. Don't re-use the same array for both uses -- or if you do, at least rename it.
    • Closing your file with fclose(fp) once you're done with it is a good idea, as I've mentioned before.
    • A newline is printed with \n, not /n.

    The other posters in this thread are right, though. You need to learn how to do this yourself. Sure, you might not be able to get the whole thing down on your first try. But with the help of tutorials, books, and references you ought to be able to do better than you have done.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  14. #59
    Registered User
    Join Date
    Nov 2007
    Posts
    38
    *sigh* Alright so after some hardcore reading and asking questions I finally damn got it lol. Now I'm not one to start trouble, but it does the same exact thing as my original program, haha. I do see the differences however when it was finally all done. Ill admit, I suck at programming, but when I have my moments damn I'm good lol.

    Anyhow I have one more qualm with this program. I put in an else statement for if the file didnt exist, cuz it seemed like a good idea, and it gives me a parse error before 'else'. So what is holding me back this time fellas? Heres the code:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    { 
    
    	FILE *fp;
    	char arr[200];
    	int filename;
    	int numLines;
    	const int MAX_LINES = 1;
        for (filename=1;filename<argc;filename++)
    	{ 
             fp=fopen(argv[filename], "r");
    
             if (fp !=NULL) {
                for(numLines=1;numLines<=MAX_LINES;numLines++)
                   {
                     fgets(arr,200,fp);
                     fputs(arr,stdout);
                   }
                                  }
             }
             else 
    	fprintf(stderr, "The file %s doesn't exist/n", argv[filename])
          
    
    }
    Thanks again guys for the help and putting up with me lol.

  15. #60
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You're getting there, but there are a few problems yet.
    "/n" isn't the newline char. "\n" is.
    Your indentation is horrible and may have caught you off gaurd. Let me clear it up a little and you'll see that you'll most likely find a bug.
    Btw, you also forgot ; on the fprintf line.

    Quote Originally Posted by CrazyShellsSlam View Post
    *sigh* Alright so after some hardcore reading and asking questions I finally damn got it lol. Now I'm not one to start trouble, but it does the same exact thing as my original program, haha. I do see the differences however when it was finally all done. Ill admit, I suck at programming, but when I have my moments damn I'm good lol.

    Anyhow I have one more qualm with this program. I put in an else statement for if the file didnt exist, cuz it seemed like a good idea, and it gives me a parse error before 'else'. So what is holding me back this time fellas? Heres the code:

    Code:
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    { 
    	FILE *fp;
    	char arr[200];
    	int filename;
    	int numLines;
    	const int MAX_LINES = 1;
    	for (filename = 1; filename < argc; filename++)
    	{ 
    		fp = fopen(argv[filename], "r");
    		if (fp != NULL)
    		{
    			for(numLines = 1; numLines <= MAX_LINES; numLines++)
    			{
    				fgets(arr, sizeof(arr), fp);
    				fputs(arr, stdout);
    			}
    		}
             }
    	else 
    		fprintf(stderr, "The file &#37;s doesn't exist/n", argv[filename])
    }
    Thanks again guys for the help and putting up with me lol.
    It's also better to use sizeof(arr) instead of the actual size in case you change the size later. Even if it not, it's always a good programming practice.
    Do proper indenting and you'll see it catches a lot of bugs!
    (Can you see where the actual error is yet?)

Popular pages Recent additions subscribe to a feed