Thread: basic programming for some but sooo hard for me

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    13

    Angry basic programming for some but sooo hard for me

    Hi, im hoping someone will take pity on me, for my uni course i have to pass a C Programming assessment but im failing at the first hurdle... I know nothing about C but I will fail my full course

    anyway to my question

    the thing i need to know is.

    is it possible to get a user to specify a text file to open create a copy and save it so i can do various things to it

    i really need to know how to do this, even a link to an article or paper which describes this function would really help

    i can find loads of code on everything else but none on this (unless im looking for the wrong thing) some of the other things i need to do is remove all none standard characters, replace sole instance i with capital I add full stops to the end of a sentence and add a Capital at the start of a sentence, create two lines between each paragraph and create a counter that will count the words, spaces, paragraphs, quotation marks etc

    i really think i can do this if i can just get some code to get the user to specify the file and create a copy that i could work with

    im sorry if this is the wrong section or even if this request is not acceptable but im desperate

    any help would be brilliant even if you can just suggest the commands i need to use

    just to clarify im looking for help on

    is it possible to get a user to specify a text file to open create a copy and save it so i can do various things to it
    Last edited by Boogyman; 02-21-2010 at 07:53 PM. Reason: clarification

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Well of course!

    Code:
    FILE *fp;
    char filename[80];
    
    scanf("%s", filename);
    getchar(); //pull off the newline from the keyboard buffer
    
    if((fp = fopen(filename, "rt")) == NULL) {
      printf("\nFile failed to open - terminating");
      //either return 1 or exit, here
    }
    
    //Rest of your code
    There are some caveats that go along with this. If you want to use a backslash, that is an escape (special) character in C, so you need to use TWO of them: \\, to "get" the effect of one inside a string or char.

    When you want to work with the file, I would strongly recommend doing that work while the text is in a char array you create for that purpose. The sequential way that you have to work with a file, makes that MUCH more difficult to work with data, while it's in the file.

    When you're done with the char's you have in the array, then write those out to a new file, and get some more char's, if needed.

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    13
    Code:
    #include <stdio.h>
    
    
    FILE * fte;				// points to a file called fte (file to edit)
    
    main(void)
    {
     char name[50];
    
    	printf("Enter the name of file to open ");		// issues the command to enter the file name
     	gets(name);			// gets the file name from the user
    	fte=fopen(name,"r");	// gives the command to open the predefined name
        
     	{
        	if (fte==NULL)			// it tests the file to see if its open if its not it will advise the following message
     		printf("ERROR - cannot open file please try again %s");	// gives out an error message 
    		else;
        }
        return 0;
    }
    this is what i have so far... im concerned that my attempt is sooo different from yours have you any hints on making a copy?

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I usually use a char array[100], and then a while loop:

    Code:
    while(fgets(array, sizeof(array), filePointer)) {
      fprintf(filePointer, "%s", array);
    }
    
    fclose(filePointer);
    fgets returns NULL when the file is empty, so that works OK.

  5. #5
    Registered User
    Join Date
    Feb 2010
    Posts
    13
    is there a way to use fprintf to take the data from the file pointer to a new file? im going around in circles and have been told i need to use fprintf but i really dont know how to do it

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Boogyman View Post
    is there a way to use fprintf to take the data from the file pointer to a new file? im going around in circles and have been told i need to use fprintf but i really dont know how to do it
    You can't take data "from the file pointer", because the file pointer has no file data. It has a struct with members like the address of the stream, the file mode being used, etc.

    What you want is to take the data from the file, and put it into a char array, then you can use fprintf() to pint the char array's contents, to a file.

    fprintf() works like printf(), except the first parameter for it, is the name of the file pointer that has opened the file:

    Add this to the while loop I posted above, and you have the basics for copying a file. Note that this file pointer is fp2, (file pointer 2), and should be set with an open file mode of write, instead of read. Meaning you have to have two file pointers: fp (for input), and fp2 (for the output).

    Code:
    fprintf(fp2, "%s", charArray);

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Boogyman View Post
    is there a way to use fprintf to take the data from the file pointer to a new file?
    So maybe you want TWO file pointers (2 files...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

  8. #8
    Registered User
    Join Date
    Feb 2010
    Posts
    13

    still confused

    hi sorry for being a pain but im still really stuck
    so far i have

    Code:
    #include <stdio.h>
    
    
    FILE * fte;				// points to a file called fte (file to edit)
    FILE * cfte;                              // points to a file called ctfe copy file to edit)
    char array[100];
    char name[50];                       // receives the file name to open from the user
    char name1[50];                     // receives the file name to save as from the user
    main(void)
    
    {
    
    printf("Enter the name of file to open ");	 // issues the command to enter the file name
    gets(name);      					 // gets the file name from the user
    fte=fopen(name,"r");			         // gives the command to open the predefined name
        
     	{
    if (fte==NULL)					         // tests the file to see if its open if its not it will advise the following message
    printf("ERROR - cannot open file please try again %s");	// gives out an error message else;
        }
    printf ("Enter the name you wish to call the new file");	// asks for a name to call the new file
    gets(name1);						// gets the name for the new file
    cfte=fopen(name1,"r");				// opens the file name1
    cfte=fprintf(name1,"w");				// creates the file from the data with the name specified in name1
    {
    if (cfte==NULL)						//checks the file has written
    printf("Error cannot write new file! please try again%s");	// relays a message if the file is not written
            
    }
    while(fgets(array, sizeof(array), cfte)) 						//uses fgets 
    {
    fprintf(fte, "%s", array);
    fprintf(cfte, "%s",array);
    
    }
    fclose(fte);
    
    return 0;
    }
    i really cant get it to work, I think i understand what its doing but its not doing it.. I cant get to grips with writing to the file.. its all over the place but i think im getting there with your help please could you point me in the right direction

  9. #9
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You need to start indenting properly: it will make life easier for you and everyone else. Do that and post again. Do not pass GO. Do not collect $200.
    Code:
    #include <stdio.h>
    
    
    FILE * fte;				// points to a file called fte (file to edit)
    FILE * cfte;                              // points to a file called ctfe copy file to edit)
    char array[100];
    char name[50];                       // receives the file name to open from the user
    char name1[50];                     // receives the file name to save as from the user
    
    main(void)
    {
    	printf("Enter the name of file to open ");	 // issues the command to enter the file name
    	gets(name);      					 // gets the file name from the user
    	fte=fopen(name,"r");			         // gives the command to open the predefined name
     	{
    		if (fte==NULL)					         // tests the file to see if its open if its not it will advise the following message
    		printf("ERROR - cannot open file please try again %s");	// gives out an error message else;
            }
    Starting to look interesting already, if you see my point.
    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
    Registered User
    Join Date
    Feb 2010
    Posts
    13
    Hi sorry... it was indented when i started because i do it with the editor i use but whenever i copy and paste in here it screws up will try my best next time I post... my fault for being lazy and just copy and pasting the thing
    Last edited by Boogyman; 02-22-2010 at 08:43 PM. Reason: cleaning up some code

  11. #11
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Okay, well I guess that could happen but what's up with that first block?
    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
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Boogyman, don't squish all your lines of code over to the left hand side. Subordinate lines of code should be indented 2 to 5 spaces.

    That will improve reading and understanding, for you and everyone on the forum (or anywhere else).

    Try this:
    Code:
    #include <stdio.h>
    
    
    FILE * fpIn;				// points to a file called fte (file to edit)
    FILE * fpOut;                              // points to a file called ctfe copy file to edit)
    char array[100];
    char filename[50];                       // receives the file name to open from the user
    //filename1 is "boogey1.txt"                  
    
    int main(void)
    
    {
    
       printf("Enter the name of file to open ");	 
       gets(filename);      			// gets the file name from the user
       fpIn=fopen(filename,"r");			// opens the file
        
     	
       if (fpIn==NULL)		//tests if its open
          printf("ERROR - cannot open file please try again %s");	
       
       printf ("Enter the name you wish to call the new file");
       gets(filename);					
    
       fpOut=fopen(filename,"w");				//opens file in write mode
    
       if (fpOut==NULL)					
          printf("Error cannot write new file! please try again%s");	
            
       while(fgets(array, sizeof(array), fpIn))  	//gets one line of text & puts it into the array 
       {
          fprintf(fpOut, "%s", array);              //writes array string to the output file
       }
    
       //closing both files
       fclose(fpIn);
       fclose(fpOut);
    
       return 0;
    }
    I "recycled" filename[]" for both filenames, and renamed the name[] and file pointers to something that made sense to me.

    I recommend:

    Get yourself a beginner's book, like Horton's "Beginning C", and go through it.

    Stop translating every line of code into commented non-code. It's way annoying, and you need to get thinking "in code", not "translate to English (or any other non-C language). You'll never be good at ANY new language if you keep translating everything back to your native language.

    Perro in Spanish, does not mean "dog". It means "perro", and you need to think "perro" not "what would that be in English? oh yeah, dog".

    Use CONCISE comments for the exceptional or to note some part of the flow of the program, at that point in the program. Let the code be the main star of your program. If you need more, add a note section before each function.

    Avoid ANYTHING that isn't clear - ctfe file pointers, for instance. Names like that just don't "stick" and will cause endless confusion and bugs.

    Edit: It's fixed now.
    Last edited by Adak; 02-22-2010 at 09:19 PM.

  13. #13
    Registered User
    Join Date
    Feb 2010
    Posts
    13
    Thankyou guys for all your help I really appreciate it, lets just say My lecturer is blind to the fact that none of the students in his class apart from two know how to programme C, hes the one who keeps telling me to note every line so that it shows what i am doing, you guys have helped me more in 2 days than he has in 15 weeks, I have just ordered that book from amazon, thing is he has given us till friday after noon to:

    Ask user to input the filename to open
    Use the input to open the file
    Ask the user to input a file name to save
    Create the file from the name that the user suggested
    Use the file that is copied to complete the operations
    • Remove the illegal characters
    • Delete the sole lowercase i and replace with uppercase I
    • Make sure that all sentences start with a capital letter
    • Make sure that all sentences end with a full stop
    • Make sure that new paragraphs are two line spaces rather than one
    Create a report at the end that will count
    • How many lines the file contains
    • How many words the file contains
    • How many spaces the file contains
    • How many characters the file contains
    • How many punctuation marks are in the text
    • How many changes were made
    • How many characters substitutions or corrections were made

    now i guess you can see why im in a massive panic and have stayed up for 2 days reading books and more books and more books im at a point where its time to sleep for a few hours before i spend 9 hours at uni without a break in 8 hours

    thankyou guys again for the valuable help i will keep you updated on how i go over the next few days and will hopefully have something to show you by friday (im looking for a shooting star to wish upon as we speak lol)


    sorry i keep getting the error if i try using gcc
    C:\cprog>gcc test86.c -o test86.exe
    test86.c: In function `main':
    test86.c:25: warning: passing arg 1 of `fprintf' from incompatible pointer type
    test86.c:25: warning: assignment makes pointer from integer without a cast

    these are totally new errors to me

    this is what i get if i try using borland compiler
    C:\Borland\BCC55\Bin\bcc32.exe -c -q -O1 -v -WC -wdef -wnod -wamp -wprc -wuse -IC:\Borland\BCC55\include test00.c

    test86.c:
    Warning W8075 test86.c 25: Suspicious pointer conversion in function main
    Warning W8069 test86.c 25: Nonportable pointer conversion in function main

    its the line which reads
    fpOut=fprintf(filename,"w");

    sorry for all the editing
    Last edited by Boogyman; 02-22-2010 at 09:01 PM.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I will check that code, in just a minute. (in Borland).

    Your assignment sounds daunting, but it can be done easily, if you keep it SIMPLE and CLEAR. For now, I suggest you get some sleep, and re-group when you're at your best. Friday is plenty of time. The hard part is done, imo.

  15. #15
    Registered User
    Join Date
    Feb 2010
    Posts
    13
    Thankyou i will get some sleep again the help is most appreciated im just glad i found a site that has such helpful people

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [ANN] New script engine (Basic sintax)
    By MKTMK in forum C++ Programming
    Replies: 1
    Last Post: 11-01-2005, 10:28 AM
  2. what are your thoughts on visual basic?
    By orion- in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 09-22-2005, 04:28 AM
  3. Replies: 2
    Last Post: 07-06-2005, 07:11 PM

Tags for this Thread