Reputation: 15
I have this file that has just numbers:
0 1 2 3 4 5
5 6 7 8 9 10
I've made this function to write into the file:
void change(char* file) {
int count = 0;
FILE* arquive = fopen (file,"a+");
char line[256];
memset(line,0,strlen(line));
char auxLine[256];
memset(auxLine,0,strlen(auxLine));
while (fgets(line, sizeof(line), arquive) != NULL) {
if (count == 1) {
memset(auxLine,0,strlen(auxLine));
strncpy(auxLine, line, sizeof line);
fprintf(arquive, "%s", auxLine);
} else {
count++;
}
}
}
The output on the file:
5 6 7 8 9 105 6 7 8 9 10
10
2 10
2 10
9 9 16 16 NULL NULL NULL NULL
But whenever I try to append a string to the file using fprintf, it prints a lot of trash. I've tried using memset to clean whats inside, but without any success.
Thanks for your help!
Upvotes: 0
Views: 67
Reputation: 10435
fopen(..., "a+") -- Open for reading and writing. The stream is positioned at the end of the file. So, your while loop is never entered.
The copies and memsets are meaningless, the code below is equivalent:
void change(char* file) {
int count = 0;
FILE* arquive = fopen (file,"a+");
char line[256];
while (fgets(line, sizeof(line), arquive) != NULL) {
if (count == 1) {
fputs(line, arquive);
} else {
count++;
}
}
}
void change(char* file) {
int count = 0;
FILE* arquive = fopen (file,"a+");
FILE *src = fopen(file, "r");
char line[256];
while (fgets(line, sizeof(line), src) != NULL) {
if (count == 1) {
fputs(line, arquive);
} else {
count++;
}
}
fclose(src);
fclose(arquive);
}
Upvotes: 2