Writing within a loop

This is a discussion on Writing within a loop within the C Programming forums, part of the General Programming Boards category; This code is supposed to run through a loop and write data to a file descriptor. Code: #include <stdio.h> #include ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    11

    Writing within a loop

    This code is supposed to run through a loop and write data to a file descriptor.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    
    void format(int n, char *d, FILE *f);
    
    int main()
    {
    
    char *d="written";
    FILE *f;
    int i, n=0;
    
    for(i=0; i<=5; i++)
    {
    
    	format(n, d, f);
    
    	fprintf(f, "stack #1, 15");
    	fclose(f);
    
    }
    
         return 0;
    
    }
    
    void format(int n, char *d, FILE *f)
    {
    
    char fm[16];
    
    	n++;
    	snprintf(fm, 16, "%s.%d.txt", d, n);
    	f = fopen(fm, "w");
    
    }
    When I run this program I get a "segmentation fault" and I'm not sure why. I'm guessing it has to do with format().

    How can I use format() to correctly write data to a fd?

    Thanks!

  2. #2
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    You haven't opened the file. While calling format you've just passed a _copy_ of f. Try this;

    Code:
    int main(void)
    {
        ....
            format(n, d, &f);
        ....
    }
    
    void format(int n, char *d, FILE **f)
    {
        ...
        *f = fopen(fm, "w");
    }

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    11
    Thank you very much, works perfectly!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 11:44 AM
  2. Visual Studio Express / Windows SDK?
    By cyberfish in forum C++ Programming
    Replies: 23
    Last Post: 01-22-2009, 02:13 AM
  3. Replies: 8
    Last Post: 12-01-2008, 10:09 AM
  4. syntax question
    By cyph1e in forum C Programming
    Replies: 19
    Last Post: 03-31-2006, 12:59 AM
  5. when a while loop will stop ?
    By blue_gene in forum C Programming
    Replies: 13
    Last Post: 04-20-2004, 04:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21