Al.
Al.

Reputation: 53

appending in C failing, simply overwriting

Instead of appending "abc" (and thus eventually getting a file full of abcabcabc....), no matter how many times I run this, myfile only containst "abc".... how can I append?

#include <stdio.h>
#include <string.h>

int main(){
    char strng[10];
    strcpy(strng,"abc");
    FILE *my_file;
    my_file = fopen("myfile","a+");
    if (my_file == NULL){ printf("problem\n");}
    fwrite(strng, sizeof(strng), 1, my_file);
    printf("appending %s\n",strng);
    fclose(my_file);
}

Upvotes: 4

Views: 11393

Answers (4)

MBO
MBO

Reputation: 30985

That program works and does what you said to do: append 10 characters (sizeof(strng)) to file, including \0 and rest of the array. Change sizeof to strlen.

Besides that you should not only print "problem" when you can't open file, but also not write to it.

And last problem in your code - you declared main as returning int, but end program without setting return code. If you end program correctly, always return EXIT_SUCCESS.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUF_SIZE 10
char buf[BUF_SIZE];

int main(int ac, char **av) {
    FILE *my_file;

    strncpy(buf, "abc", BUF_SIZE-1);
    buf[BUF_SIZE-1] = '\0';
    my_file = fopen("myfile", "a+");
    if (my_file == NULL) {
        fprintf(stderr, "problem opening file\n");
        return EXIT_FAILURE;
    } else {
        fwrite(buf, strlen(buf), 1, my_file);
        printf("appending %s\n", buf);
        fclose(my_file);
        return EXIT_SUCCESS;
    }
} 

Upvotes: 1

Tony van der Peet
Tony van der Peet

Reputation: 824

When you fopen the file, the stream position is at the beginning of the file. Surely you have to seek to the end before writing in order to get the string appended?

Upvotes: -1

Mike Dunlavey
Mike Dunlavey

Reputation: 40659

Don't use sizeof, use strlen. sizeof is 10, so you're writing "abc\0\0\0\0\0\0\0".

Upvotes: 0

anon
anon

Reputation:

Apart from the fact that:

fwrite(strng, sizeof(strng), 1, my_file);

should be:

fwrite(strng, strlen(strng), 1, my_file);

it works for me.

Upvotes: 4

Related Questions