Thread: could you help with me C code?thanks,a little urgent.

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    42
    i got stuck with my C programming homework, i cannot work them out.
    all of them got some errors
    could someone help with me?thanks!any help is appreciated.

    Exercise 1
    Write a file copy program that copies an existing file into another file. The program should ask the user to enter the source file name and destination file name. The file copy should be performed in binary mode. Use fseek() to move within the source file and ftell() to determine the size of the file (if needed). Read the data from the source file and write the values read in the destination file in a loop. Read and write data in blocks of 1024 bytes.


    below is my work.

    Code:
    #include<stdio.h> 
    #include<conio.h> 
    #include<string.h>      // for strlen() function. 
    #include<stdlib.h>      // for exit() function. 
    
    
    
    int main()   
    {  
    	int data[1024];
    	char   sourcename[20];  
    	char   destinationname[20]; 
    	FILE   *sFile,*dFile;   
    	long t;
    	
    	
     char sourcename[20];
    	printf("please input source filename");
     gets(sourcename);
     char destinationname[20];
    	printf("please input destination filename");
     gets(destinationname);
    	
    
     if((sFile=fopen(sourcename,"rb"))==NULL)   
     {   
      printf("fail to open source file\n");   
      exit(0);   
     }
       
     if((dFile=fopen(destinationname,"wb"))==NULL)   
     {   
      printf("fail to open destination file\n");   
      exit(0);   
     }   
    	
    	fseek(sFile,0L,SEEK_END);
    	t=ftell(sFile);  //get the size of the file.
    #if 0	
    	for(;(feof(sFile)!=0);)
    	{
    		fread(data,sizeof(data),1,sFile);
    		printf("%s",sFile);
    fwrite(data,strlen(data),1,dFile);
    		printf("%s",dFile);
    	}
    #else 
    	while (1) {
    		fread(data,sizeof(data),1,sFile);
    		fwrite(block,strlen(data),1,dFile);
    		if(feof(sFile)==0)
    			break;
    		}
    	
    #endif
    	}
     fclose(sFile);   
     fclose(dFile);
    	getch();
     return(0);   
    }
    thanks
    Last edited by hth373737; 11-23-2008 at 06:31 AM. Reason: only one assign for one thread

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Code:
    	while (1) {
    		fread(data,sizeof(data),1,sFile);
    		fwrite(block,strlen(data),1,dFile);
    		if(feof(sFile)==0)
    			break;
    		}
    This is incorrect in several ways:
    1. You read into "data", then write out "block".
    2. You do not take into account the amount of data that was actually read.
    3. You assume that strlen() works on data read by fread() - since the data you are reading is the binary content of an arbitrary file, it makes absolutely no sense to assume that strlen() will give anything useful at all. Further, should your data variable not contain a zero byte within the block you read, strlen will continue reading memory beyond the end of the data, which will lead to one of two things: a crash because you are reading invalid memory location (the memory doesn't actually exist) or you get a length longer than your data buffer - both will absolutely lead to incorrect content in the destination file.

    I'm not going to discuss more than one exercise at a time, because it will just confuse you.

    --
    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.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    So take your assignments one at a time, and tell us what the problems are!

    If you just dump your code, I'll just dump your request for helpl. Show us that you're involved and working/thinking on this.

    We're not here to just take your code, and your description of "it has errors", or "it doesn't work", and do your homework for you.

    What problems do you have with #1?

  4. #4
    Registered User
    Join Date
    Nov 2008
    Posts
    42
    Quote Originally Posted by matsp View Post
    Code:
    	while (1) {
    		fread(data,sizeof(data),1,sFile);
    		fwrite(block,strlen(data),1,dFile);
    		if(feof(sFile)==0)
    			break;
    		}
    This is incorrect in several ways:
    1. You read into "data", then write out "block".
    2. You do not take into account the amount of data that was actually read.
    3. You assume that strlen() works on data read by fread() - since the data you are reading is the binary content of an arbitrary file, it makes absolutely no sense to assume that strlen() will give anything useful at all. Further, should your data variable not contain a zero byte within the block you read, strlen will continue reading memory beyond the end of the data, which will lead to one of two things: a crash because you are reading invalid memory location (the memory doesn't actually exist) or you get a length longer than your data buffer - both will absolutely lead to incorrect content in the destination file.

    I'm not going to discuss more than one exercise at a time, because it will just confuse you.

    --
    Mats
    for #1, i don't know how to read data from sourse and copy that into destination in a loop.
    i got confused about that "blocks" of 1024 bytes.
    from your suggenstion, i know about strlen() will read zero byte. but i don't know how to avoid it.

  5. #5
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    but i don't know how to avoid it.
    Check the return value of fread and use it
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by hth373737 View Post
    for #1, i don't know how to read data from sourse and copy that into destination in a loop.
    i got confused about that "blocks" of 1024 bytes.
    from your suggenstion, i know about strlen() will read zero byte. but i don't know how to avoid it.
    The function fread() will actually return how many items it read. So you may want to set the size of each item to 1, and number of items to the size of the block, and then use the returned value to tell fwrite how much to write out.

    There is no need to copy the data into a different place before passing it to fwrite - why do you think you need to do that?

    strlen only works if the data actually ends with a zero, and whilst random data MAY contain a zero somewhere within the data you have read, it is by no means guaranteed that it will, and more so, it is unlikely to be at the end of the data.

    --
    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.

  7. #7
    Registered User
    Join Date
    Nov 2008
    Posts
    42
    Quote Originally Posted by Adak View Post
    So take your assignments one at a time, and tell us what the problems are!

    If you just dump your code, I'll just dump your request for helpl. Show us that you're involved and working/thinking on this.

    We're not here to just take your code, and your description of "it has errors", or "it doesn't work", and do your homework for you.

    What problems do you have with #1?
    thanks for your suggentions.
    10-1.c:2:19: error: conio.h: No such file or directory
    10-1.c: In function ‘main’:
    10-1.c:17: error: redeclaration of ‘sourcename’ with no linkage
    10-1.c:11: error: previous declaration of ‘sourcename’ was here
    10-1.c:20: error: redeclaration of ‘destinationname’ with no linkage
    10-1.c:12: error: previous declaration of ‘destinationname’ was here
    10-1.c:50: error: ‘block’ undeclared (first use in this function)
    10-1.c:50: error: (Each undeclared identifier is reported only once
    10-1.c:50: error: for each function it appears in.)
    10-1.c:50: warning: passing argument 1 of ‘strlen’ from incompatible pointer type
    10-1.c: At top level:
    10-1.c:57: warning: parameter names (without types) in function declaration
    10-1.c:57: warning: data definition has no type or storage class
    10-1.c:58: warning: parameter names (without types) in function declaration
    10-1.c:58: warning: data definition has no type or storage class
    10-1.c:59: warning: data definition has no type or storage class
    10-1.c:60: error: syntax error before ‘return’

    all of this are the errors from the compiler.

    i got confused about the process to read and write data in blocks 1024 in a loop.

  8. #8
    Registered User
    Join Date
    Nov 2008
    Posts
    42

    Unhappy

    Quote Originally Posted by matsp View Post
    The function fread() will actually return how many items it read. So you may want to set the size of each item to 1, and number of items to the size of the block, and then use the returned value to tell fwrite how much to write out.

    There is no need to copy the data into a different place before passing it to fwrite - why do you think you need to do that?

    strlen only works if the data actually ends with a zero, and whilst random data MAY contain a zero somewhere within the data you have read, it is by no means guaranteed that it will, and more so, it is unlikely to be at the end of the data.

    --
    Mats
    i was to size the data and pass it to the new file. if strlen is not used,how can i size it and copy that with blocks 1024?

    in fact, i am not fully understand what you said..

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    [code]
    char sourcename[20];
    char destinationname[20];
    FILE *sFile,*dFile;
    long t;


    char sourcename[20];
    This is your first error.
    Second one is similar.

    Line 50 you use a variable called block which you haven't declared (and you don't need it, as "data" is probably the right thing, unless I've misunderstood completely what you are trying to do).

    i was to size the data and pass it to the new file. if strlen is not used,how can i size it and copy that with blocks 1024?

    in fact, i am not fully understand what you said..
    Sorry, I'll try again:
    If you swap the size arguments you give to fread, you will get the EXACT number of bytes that fread has read into the data array. So if you pass the value you got back from fread into fwrite, you don't need to do anything more. [Just check that it's greater than zero, as zero or a negative number indicates that no data was read and an error occurred respectively].

    --
    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. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by hth373737 View Post
    for #1, i don't know how to read data from sourse and copy that into destination in a loop.
    i got confused about that "blocks" of 1024 bytes.
    from your suggenstion, i know about strlen() will read zero byte. but i don't know how to avoid it.
    Here's an example that might help you out:

    Code:
    #include <string.h>
    #include <stdio.h>
    
    int main(void)
    {
       FILE *stream;
       char msg[] = "this is a test";
       char buf[20];
    
       if ((stream = fopen("DUMMY.FIL", "w+"))
           == NULL)
       {
          fprintf(stderr, "Cannot open output file.\n");
          return 1;
       }
    
       /* write some data to the file */
       fwrite(msg, strlen(msg)+1, 1, stream);
    
       /* seek to the beginning of the file */
       fseek(stream, SEEK_SET, 0);
    
       /* read the data and display it */
       fread(buf, strlen(msg)+1, 1, stream);
       printf("&#37;s\n", buf);
    
       fclose(stream);
       return 0;
    }
    A while loop could be used nicely to read in your blocks of data. Every block that you read in, you turn right around and write it out, again in binary format, with fwrite(). Then get another block of data with fread()

    The number 1 just before "stream" is the number of blocks (of the size you have specified), that fread will attempt to read. On EOF (End Of File), fread() will return a number less than the one you have specified (zero I expect).

    So the number 1 is the key to using fread() in a while loop:

    Code:
    while((fread(all the normal stuff here)) > 0)  {
        write out your block of data, in here.
    
    }
    I'm no expert on binary file copying, but the above looks like a good place to start for your loop.


    Study these details and see how buff, msg, the +1, and stream, all work together.

    Edit: You don't have Turbo C, so get rid of the #include <conio.h>. You won't need it anywhere for this assignment.
    Last edited by Adak; 11-23-2008 at 07:02 AM.

  11. #11
    Registered User
    Join Date
    Nov 2008
    Posts
    42
    Quote Originally Posted by matsp View Post
    [code]
    char sourcename[20];
    char destinationname[20];
    FILE *sFile,*dFile;
    long t;


    char sourcename[20];
    This is your first error.
    Second one is similar.

    Line 50 you use a variable called block which you haven't declared (and you don't need it, as "data" is probably the right thing, unless I've misunderstood completely what you are trying to do).



    Sorry, I'll try again:
    If you swap the size arguments you give to fread, you will get the EXACT number of bytes that fread has read into the data array. So if you pass the value you got back from fread into fwrite, you don't need to do anything more. [Just check that it's greater than zero, as zero or a negative number indicates that no data was read and an error occurred respectively].

    --
    Mats
    the sourcename and destinationname i defined are for the two names of the file.
    data is used to do that 1024 bytes delivering work. sorry for not making comments for the codes.
    the "block" may be due to my buddy, i ask him for help, but i cannot solve that. pity.

  12. #12
    Registered User
    Join Date
    Nov 2008
    Posts
    42
    Quote Originally Posted by Adak View Post
    Here's an example that might help you out:

    Code:
    #include <string.h>
    #include <stdio.h>
    
    int main(void)
    {
       FILE *stream;
       char msg[] = "this is a test";
       char buf[20];
    
       if ((stream = fopen("DUMMY.FIL", "w+"))
           == NULL)
       {
          fprintf(stderr, "Cannot open output file.\n");
          return 1;
       }
    
       /* write some data to the file */
       fwrite(msg, strlen(msg)+1, 1, stream);
    
       /* seek to the beginning of the file */
       fseek(stream, SEEK_SET, 0);
    
       /* read the data and display it */
       fread(buf, strlen(msg)+1, 1, stream);
       printf("%s\n", buf);
    
       fclose(stream);
       return 0;
    }
    A while loop could be used nicely to read in your blocks of data. Every block that you read in, you turn right around and write it out, again in binary format, with fwrite(). Then get another block of data with fread()

    The number 1 just before "stream" is the number of blocks (of the size you have specified), that fread will attempt to read. On EOF (End Of File), fread() will return a number less than the one you have specified (zero I expect).

    So the number 1 is the key to using fread() in a while loop:

    Code:
    while((fread(all the normal stuff here)) > 0)  {
        write out your block of data, in here.
    
    }
    I'm no expert on binary file copying, but the above looks like a good place to start for your loop.


    Study these details and see how buff, msg, the +1, and stream, all work together.

    Edit: You don't have Turbo C, so get rid of the #include <conio.h>. You won't need it anywhere for this assignment.
    i use gcc 4.2 ver. but my work will be assess in Visual Studio. i don't know the defference between them, hope okay.

    thanks for you codes.

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Oddly, I lost my Visual Studio install to a virus that wrecked havoc with my system, so I'm back to just Turbo C right now. I can use <conio.h>, but you can't, on either gcc or VS.

    So, what's the current status of your code and errors?

  14. #14
    Registered User
    Join Date
    Nov 2008
    Posts
    42
    Quote Originally Posted by Adak View Post
    Oddly, I lost my Visual Studio install to a virus that wrecked havoc with my system, so I'm back to just Turbo C right now. I can use <conio.h>, but you can't, on either gcc or VS.

    So, what's the current status of your code and errors?
    it is a pity that, the sample you given me is not an easy one,too.
    i don't know how to change my codes for better.

    got stuck still~

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by hth373737 View Post
    it is a pity that, the sample you given me is not an easy one,too.
    i don't know how to change my codes for better.

    got stuck still~
    Post it up and show the errors from the compiler - I don't have your compiler so that may be a problem.

    Others have gcc, however.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BitWise Newbie - Needs Urgent Help
    By frodonet in forum C Programming
    Replies: 15
    Last Post: 09-26-2007, 12:58 PM
  2. display character size...(quite urgent..)
    By karthi in forum C Programming
    Replies: 10
    Last Post: 07-11-2007, 09:42 PM
  3. Help.... Urgent... Thanks!
    By weihann in forum C Programming
    Replies: 0
    Last Post: 02-27-2002, 10:15 PM