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

    Join Date
    Jun 2013
    Posts
    23
    Rep Power
    0

    How to numerotate appends in file


    My program calculates the sum of numbers from a number. Ex: 32. s=3+2=5 and prints it into a file.

    What I would like the program to do is to allow the user to repeat the cycle and for each time the user enters a number, the result to be added onto the file and be appended.

    I know this is not very specific so I will give an example. Let's say the user types in 32 the result is 5 appended into the file.
    Then the user types in 40 the result is 4 appended into the file.

    I want the content of the file to be like this:
    1. s is 5
    2. s is 4

    How to do that? Thanks.
    Here's the program.


    [spoiler]#include <stdio.h>
    int main()
    {
    int n,i,s=0;
    printf("Introduceti n-ul ");
    scanf("%d", &n);
    do
    {
    s=s+n%10;
    n=n/10;
    }
    while(n);


    FILE *file;
    file=fopen("suma.txt", "w");
    if(file != NULL)
    {
    fprintf(file, "Suma cifrelor este %d", s);
    fclose(file);
    }
    getch();
    return 0;
    }
    [/spoiler]
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,367
    Rep Power
    1870
    It's nice that you attempted to use some kind of tags, but it would be better if you actually used [code][/code] tags around your code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Location
    India
    Posts
    65
    Rep Power
    19
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX_LOOP 10
    #define NAME_OF_FILE "suma.txt"
    #define NEW_LINE '\n'
    
    int WriteDataToFile (int data);
    
    int main()
    {
        int n,i,s;
    
        for (i = 0; i < MAX_LOOP; i++) {
            s = 0;
    
            printf("Introduceti n-ul ");
            scanf("%d", &n);
    
            do{
                s=s+n%10;
                n=n/10;
            }
            while(n);
    
            if(WriteDataToFile(s)) {
                printf("There is some error while creating data to file.\n");
            }
    
            getchar();
        }
        return 0;
    }
    int WriteDataToFile(int data)
    {
        FILE *file;
        file=fopen(NAME_OF_FILE, "a");
    
        if(file != NULL) {
            fprintf(file,"Suma cifrelor este %d\n",data);
            fclose(file);
            return 0;
        } else {
            return 1;
        }
    }

IMN logo majestic logo threadwatch logo seochat tools logo