#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0

    Reading and writting files


    I was trying to make a program to read the first line of a file and write it in a new one (basically i want to copy the first line of a text file):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main ()
    {
    int count;
    char *s, ch;
    
    FILE *text;
    text = fopen("text.txt","rt");
    FILE *text2;
    text_inv = fopen("text2.txt","wt");
    
    count=0;
    while ((ch=fgetc(text))!= '\n') count++;
    
    char *fgets (char *s, int count, FILE *text);
    char *fputs (char *s, int count, FILE *text2);
    
    fclose(text2);
    fclose(text);
    }
    Can anyone help me please?
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Location
    China
    Posts
    6
    Rep Power
    0

    Some Correction


    Hey Toodd, I just made some modification to your programme.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int main(void)
    {
    
      char *s, ch;
      FILE *fp1;
      FILE *fp2;
      
      
     fp1 = fopen("text.txt","r");
     fp2 = fopen("text2.txt","w");
     
     
       while ((ch= getc(fp1))!= '\n')
        putc(ch,fp2);
    
       if (fclose(fp1) != 0 || fclose(fp2) != 0)
       fprintf(stderr, "Error in closing files\n");
        
       
       return 0;
       
    }
    It can run without any warning or error on C-free compiler.

    As far as I'm concerned, it's the problem starting from the below 2 lines. I can only go this far for the result.
    The problem in your code remains unsolved, because i cannot figure out exactly the wrong logic/syntax issues in your code.

    Code:
    count=0;
    while ((ch=fgetc(text))!= '\n') count++;
    Mich
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    The problem is that i want to make a program which write each line of the first file on the second file but in reverse order. For example:

    hello world
    this is my programme

    will appear in the second file as:

    dlrow olleh
    emmargorp ym si siht

    So my first step was to figure out how to put a line read from the first file to a string. Any idea how to do that?
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,225
    Rep Power
    2222
    Originally Posted by Toodd
    So my first step was to figure out how to put a line read from the first file to a string. Any idea how to do that?
    fgets
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    I tried the programme:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    int main(void)
    {
    
      char *s, ch;
      FILE *fp1;
      FILE *fp2;
      
      
     fp1 = fopen("text.txt","r");
     fp2 = fopen("text2.txt","w");
     
     
       while ((ch= getc(fp1))!= '\n')
        putc(ch,fp2);
    
       if (fclose(fp1) != 0 || fclose(fp2) != 0)
       fprintf(stderr, "Error in closing files\n");
        
       
       return 0;
       
    }

    but then i get the same error: segmentation fault.
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    This is my current code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    main ()
    {
    int count;
    char *s, ch;
    
    FILE *text1;
    text1 = fopen("text1.txt","r");
    FILE *text2;
    text2 = fopen("text2.txt","w");
    
    count = 10;
    
    char *fgets (char *s, int count, FILE *text1);
    
    fclose(text2);
    fclose(text1);
    }
    file text2 is created but has nothing on it. the string s is empty. Where is the error?
  12. #7
  13. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,225
    Rep Power
    2222
    You are not calling fgets. All you did was to insert its prototype. In order to use fgets, you must actually use it!

    If you have no clue how to call a function, then go back and start reading your textbook from the very beginning. That should have been one of the first things you were taught.

    Also, you neglected to indent your code. It may not make much difference in the code you posted, but it will become absolutely essential very soon.

    And you lied to the compiler:
    Originally Posted by Henry Spencer
    If you lie to the compiler, it will get its revenge.
    You implicitly declared main to return an int value, but then you broke that promise by not returning anything. Explicitly declare everything!; leave nothing to implicit default declarations! Return 0 for successful execution or a positive non-zero value if your program cannot run (eg, files fail to open, required arguments are not entered by the user).
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    main ()
    {
    	char *s;
    	FILE *text1;
    	FILE *text2;
    
    	text1 = fopen("text1.txt","r");
    	text2 = fopen("text2.txt","w");
    	
    	fgets (s, 100,text1);
    	fputs(s,text2);
    	
    	fclose(text1);
    	fclose(text2);
    }
    This is the new code. But it still doesn't work...
  16. #9
  17. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,225
    Rep Power
    2222
    But it still doesn't work...
    What does that mean?

    I'll let you in on a little known secret: We cannot read your mind! You have to actually tell us what's happening.

    Did fopen succeed in opening text1.txt? If it didn't and you try to use that file, then it will most likely cause your program to crash (is that what "it still doesn't work" means? I certainly have no way of knowing). Always test the return value of fopen before you try to use it. And don't use it if the file failed to open.

    Also, s doesn't point to valid memory. It's an uninitialized pointer. Never ever use an uninitialized variable, most especially not an uninitialized pointer! An uninitialized variable or pointer contains whatever just happens to have been stored last in that memory location, AKA garbage. s could be pointing anywhere. Using s like this is like playing a sick game of Russian Roulette in which you enter a crowded room and blindly point the gun in any random direction and shoot. You're going to overwrite memory that's being used for other purposes, thus clobbering that memory and causing erratic and "inexplicable" problems. Most of the time, it will point to memory that doesn't belong to you or that is read-only, in which case your program will crash with a SEGFAULT or an access violation.

    Declare s to be a char array of sufficient size to accommodate the largest string you anticipate reading in, plus one more for the null-terminator. Or you could malloc or calloc that amount of memory to it.
  18. #10
  19. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2013
    Posts
    24
    Rep Power
    0
    OK.

    How can I malloc or calloc the amount of memory for s, without knowing its length?
  20. #11
  21. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,225
    Rep Power
    2222
    Nothing is keeping you from allocating more than the minimum. Is the line going to be longer than 80 characters? No? So you could safely go with a size of 81.

    There's also a newer function, getline, which can allocate space for that pointer. I haven't used it, but you can find its documentation with man page getline. That would be assuming that your compiler supports it.
  22. #12
  23. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    4
    Rep Power
    0

    Thumbs up


    Originally Posted by Toodd
    OK.

    How can I malloc or calloc the amount of memory for s, without knowing its length?
    You can try something like this (based on your code):

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(void)
    {
       char *s, ch;
       FILE *fp1;
       FILE *fp2;
       int n;
      
       fp1 = fopen("text.txt","r");
       fp2 = fopen("text2.txt","w");
     
       for (n=0 ; (ch= getc(fp1))!= '\n' ; n++);
    
       rewind(fp1);
    
       s = (char *) malloc(n+1);
    
       for (n=0 ; (ch= getc(fp1))!= '\n' ; n++)
          s[n] = ch;
       s[n]='\0';
    
       for (n=n-1 ; n>=0 ; n--)
          putc(s[n],fp2);
       putc('\n',fp2);
    
       if (fclose(fp1) != 0 || fclose(fp2) != 0)
          fprintf(stderr, "Error in closing files\n");
       
       return 0;}

    Comments on this post

    • Mich Song agrees : that's cool.

IMN logo majestic logo threadwatch logo seochat tools logo