Thread: Need help with fget

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    2

    Need help with fget

    I have this problem that I need to get a string from the user and encypt it. The first step is to get the string from the user followed by the enter key. The next step is to encrypt the message at blocks of four characters ( Helllo world! would be [Hell] [o wo] [rld!]. You have to swap character 1 and 4 and 2 and 3. Then this is printed to a file. What I don't understand is how do I just do 4 at a time? I have a very basic program here that gets a sting from a user and prints it to a file. Am I on the right path with this? Should I manipulate the file or is there a step I am missing before the program writes to the file?
    Code:
     #include <stdio.h>
    #define FILENAME "encode.txt"
    main()
    {
      int c;				
      FILE *encode;					   				
      encode = fopen(FILENAME,"w");
    if (encode == NULL){
    	printf ("error opening input file\n");
    	return 1;}
    else
      printf("enter a sequence of characters followed by Return\n");
      while((c=getchar()) != '\n')
       {
          fputc ( c , encode );
        }
      fclose(encode);	
      return 0;		
    }

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    I wouldn't worry about the file at all (for now). Just read in the string from the user, then "encrypt" it, then print the result to the screen.

    You will want to read the user string into a buffer (instead of reading in character by character). Use the function fgets() for this.
    bit∙hub [bit-huhb] n. A source and destination for information.

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    I would start with making a swap function. It seems from your discription that the substrings of 4 chars each will be reversed. What should happen if the string does not even up in multiples of four though?

  4. #4
    Registered User
    Join Date
    Dec 2009
    Posts
    2
    Thank you for the quick responses. If there are three variables then 2 and 3 are swapped. If there are 2 or less they are printed as is.

  5. #5
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875

    strrev() is your friend

    Even if you have to implement it yourself:
    Code:
    #include <string.h>
    
    char *strrev(char *str)
    {
       char *p1, *p2;
    
       if (! str || ! *str)
          return str;
       for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
       {
          *p1 ^= *p2;
          *p2 ^= *p1;
          *p1 ^= *p2;
       }
       return str;
    }
    
    
    int main(int argc, char *argv[])
    {
       char *inputString = "Hello World!";
       char workBuf[5];
       int curPos = 0;
       int lastPos = curPos;
       bool bDone = false;
       while(!bDone)
       {
          if( strlen(inputString) <= curPos+4)
          {
    	 bDone = true;
          }
          memset(workBuf, 0, 5);
          strncpy(workBuf, inputString+curPos, 4);
          printf("%s", strrev(workBuf));
          curPos += 4;
          if(curPos > strlen(inputString))
          {
    	 curPos = strlen(inputString) - lastPos;
          }
          else
          {
    	 lastPos = curPos;
          }
       }
    	 printf("\nEnd Processing.\n");
       return 0;
    }
    Note this is a fast hack while I am doing other things so don't blame me if it eats your cat or something ^__^
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  6. #6
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Quote Originally Posted by jeffcobb View Post
    Even if you have to implement it yourself:

    ... code ...

    Note this is a fast hack while I am doing other things so don't blame me if it eats your cat or something ^__^
    Posting a completed homework assignment for somebody doesn't really help anyone. It hurts the ability of the student to think through the assignment on their own, and will only be beneficial to students looking for an easy way out.

    It is better to post hints (or pseudo-code) for a general solution, and then give specific help when the student hits a roadblock they cannot overcome on their own.
    bit∙hub [bit-huhb] n. A source and destination for information.

  7. #7
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Quote Originally Posted by bithub View Post
    Posting a completed homework assignment for somebody doesn't really help anyone. It hurts the ability of the student to think through the assignment on their own, and will only be beneficial to students looking for an easy way out.

    It is better to post hints (or pseudo-code) for a general solution, and then give specific help when the student hits a roadblock they cannot overcome on their own.
    Sorry. I am bad at explaining things/explain them better with code. I learn coding techniques better/faster/more thoroughly when looking at code. I forget that this does not help everyone the same and far be it from me to do someones homework for them.

    In this case I would have just thrown strrev() out there until I found that it doesn't exist on UNIX and *that* called for a home-brew version and THAT called for a test harness...

    Sigh.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  8. #8
    Registered User jeffcobb's Avatar
    Join Date
    Dec 2009
    Location
    Henderson, NV
    Posts
    875
    Only other thing I can say in my defense is that when presenting a code solution in a professional situation I develop it using a test-driven development model so the "test" for the solution kinda rides along as proof of execution. Again, I know its not what is needed or apparently desired here and shall endeavor to proof my replies better in the future.
    C/C++ Environment: GNU CC/Emacs
    Make system: CMake
    Debuggers: Valgrind/GDB

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Yo and in Mr.Cobbs defence I do not think providing an example of something should be prohibited or discouraged on a programming advice forum. If universities or whatever want to implement some kind of tracking system to prevent their students from using web resources because they are not getting sufficient education on the premises (and so, perversely, this would amount to cheating the system which is cheating you) then fine.

    But I do not think the MAJORITY of us, who ARE NOT IN SCHOOL should be penalized to protect that ridiculousness. There is nothing more annoying than finding someone's blog or tutorial or even API documentation with some long-winded and poorly written explanation of a basic, APPLIED CONCEPT wherein there is NO EXAMPLE CODE!!! For me, and I am sure many others, the surest and quickest way of learning is finding some working code and sorting it out -- indeed, very often I am given to doubt the veracity of someone's "advice" or "demonstration" when they fail to produce at least some basic example WHICH WORKS.

    Pathetic...cheers jeffcobb. Altho it would be nice if you put a bit more effort into an accompanying explanation and save the coolio stuff for another time
    Last edited by MK27; 12-14-2009 at 07:15 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    The problem isn't with providing an example per-say. It's with "HELP!" "Ok, here.".

    It's a bad idea to just hand out solutions to every question without requiring effort on the part of the OP to see that they're actually trying to work through the problem. Besides, no one is forcing you to post here.


    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by quzah View Post
    The problem isn't with providing an example per-say. It's with "HELP!" "Ok, here.".
    Yes, god knows we wouldn't want that. I don't see anyone asking someone to do their homework. I see someone with a problem looking for a solution. It is up to them what they do with it and to what extent they try to understand it.

    Of course, if you don't like providing that kind of HELP, no one is forcing you to post here either. But I think it is a little sad when you waste your time trying to discourage others from providing legitimate examples of code, because you have some kind of pedantic/ponderous/patronizing/pathetic "teaching" method in mind. You are not really a "wizard". It is not really "magic". Please.

    It's a bad idea to just hand out solutions to every question without requiring effort on the part of the OP to see that they're actually trying to work through the problem.
    Wow, thank you at least for being honest about your attitude. What were those 4 'p' words?

    I think it is better to stick with explaining and demonstrating C in a lucid manner rather than trying to psycho-analyse and second guess the "newbies" Etc
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I'm afraid I have to agree with quzah. Lots of people just copy whatever solution they get without ever understanding it.
    Obviously different people learn differently, hence we must first actually discover what type of help they need.
    And almost always is it better to post samples that do not actually directly solve the problem and then discuss that. If the OP can assimilate that information, then they are on a good way to solve the actual problem.

    But in any case, I would discourage anyone from posting a real solution directly after the question is asked.
    After all, we must challenge them a little. That makes a good programmer, to overcome challenges.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by MK27 View Post
    I see someone with a problem looking for a solution.
    Actually, if you want to be picky, and it appears you do, they asked if they were headed in the right direction. They didn't ask for it to be done for them.
    Quote Originally Posted by MK27 View Post
    But I think it is a little sad when you waste your time trying to discourage others from providing legitimate examples of code, because you have some kind of pedantic/ponderous/patronizing/pathetic "teaching" method in mind. You are not really a "wizard". It is not really "magic". Please.
    Show me again where I'm "discouraging others from providing legitimate examples of code".
    Quote Originally Posted by MK27 View Post
    What were those 4 'p' words?
    And by this point in this discussion, no one knows what the hell you're going on about. If you want to pick a fight with me, and it seems you do from what I've read of your posts regarding me, then have at it already. Otherwise, shut the ........ up.


    Quzah.
    Hope is the first step on the road to disappointment.

  14. #14
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Elysia View Post
    But in any case, I would discourage anyone from posting a real solution directly after the question is asked.
    After all, we must challenge them a little. That makes a good programmer, to overcome challenges.
    That's ridiculous. There are plenty of other realms in life in which you can beat around bushes and play games with people. If you want to do that here as well, terrific, but please do not tell people they cannot provide a "straight answer to a straight question" instead.

    There is also no end to the "puzzling scenarios" you can encounter while programming, so there is no need to contribute MORE to this. Anyone who is serious about programming will find PLENTY of opportunities to do challenging problem solving on their own, you do not have to provide them with more. A programming forum is somewhere you go when you are at your "wit's end", so to speak. Nice to get past the trivialities quickly and get to the legitimately interesting challanges.

    If someone does just want to copy code and not think about it, so what? That's their problem. You do not have to engage in social engineering because you are convinced everyone is just trying to cheat on a homework assignment.

    Part of the reason I bring this up is because someone just pulled this one on me on another forum, vis "clearly you are a student who just wants an answer to his question". What BS paranoid crap is that? Yeah, I'm asking for a quick solution to a simple question, hopefully including a quick simple example. That's all. I will understand it. I have plenty of REAL "challanges" to deal with. I do not need basic things obfuscated and mystified by someone who thinks wasting two hours on something that should only take 5 minutes will "teach me something".

    Being helpful should mean sharing knowledge, NOT with-holding it.

    Quote Originally Posted by quzah View Post
    Actually, if you want to be picky, and it appears you do, they asked if they were headed in the right direction. They didn't ask for it to be done for them..
    Point taken, and you're mostly a helpful guy IMO quzah, if snarky, which I don't mind that at all. My earlier comment about being Mr. Mean was a joke

    But there should be room for the jeffcobbs of the world as well, without having to belittle and/or censure them.
    Last edited by MK27; 12-15-2009 at 01:29 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It was a shame that you were treated like you were. However, I would think that whoever was replying was at fault rather than the rule for homework. Obviously they mistook you for someone looking for some homework help.
    Sharing knowledge is vital and is also why we are here. But there is also sharing too much knowledge if the individual in question has too little understanding. This is a fine line which requires careful guidelines, I think.

    I understand your argument, but I would rather guide a newbie to a solution instead of giving them. To experienced programmers, I would give a solution I know of, because I would know they would ask if they didn't understand something of the solution.
    And if they simply don't have the required knowledge... well, I can see that you can draw a parallel here to newbies. I consider it safer to give knowledge to experienced programmers, however.
    I do know very well how newbies to programming often behave, especially when given solutions. There are a lot of them, and we wouldn't do the world a favor if we let those out into the market.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with fget and simultaneous printf.
    By Ironic in forum C Programming
    Replies: 13
    Last Post: 12-08-2008, 11:05 PM
  2. Fget to list
    By Yannick in forum C Programming
    Replies: 3
    Last Post: 06-16-2008, 01:06 PM
  3. fget question
    By norhos in forum C Programming
    Replies: 6
    Last Post: 03-14-2008, 12:55 AM
  4. fgets
    By CaN Opner in forum C Programming
    Replies: 8
    Last Post: 01-14-2003, 11:58 PM