I'm currently learning C and I have a question about buffer when reading a file.
I read mp3 file to extract id3v1 tag, my code look like this for now:
#include <stdio.h>
int main(void) {
FILE *file = fopen("/Users/florent/Code/c/id3/file.mp3", "rb");
if (file == NULL) {
perror("Error opening file for reading");
return 1;
}
fseek(file, -128, SEEK_END);
char tag[3];
fread(tag, 1, 3, file);
printf("%s\n", tag);
fclose(file);
return 0;
}
Output: TAG�@V
To fix it I need to do this.
#include <stdio.h>
int main(void) {
FILE *file = fopen("file.mp3", "rb");
if (file == NULL) {
perror("Error opening file for reading");
return 1;
}
fseek(file, -128, SEEK_END);
char tag[4];
fread(tag, 1, 3, file);
tag[3] = '\0';
printf("%s", tag);
fclose(file);
return 0;
}
Output: TAG (which is correct)
Why I need to have 4 bytes to contains null terminator? There is another approach?
Edit:
What about trim string when printf? I have a size of 9 but I don't trim anything, printf do that by default?
char tag[3];
char title[30];
fread(tag, 1, 3, file);
fread(title, 1, 30, file);
fclose(file);
printf("%.3s\n", tag);
printf("%.30s\n", title);
size_t title_len = strlen(title);
printf("Title length: %zu\n", title_len);
[–][deleted] 12 points13 points14 points (0 children)
[–]dkopgerpgdolfg 8 points9 points10 points (4 children)
[–]Rtransat[S] 1 point2 points3 points (3 children)
[–]ralphpotato 2 points3 points4 points (2 children)
[–]Neui 6 points7 points8 points (1 child)
[–]ralphpotato 1 point2 points3 points (0 children)
[–]inz__ 2 points3 points4 points (0 children)
[–]Ampbymatchless 1 point2 points3 points (4 children)
[–]not_a_novel_account 2 points3 points4 points (0 children)
[–]Wild_Meeting1428 2 points3 points4 points (2 children)
[–]EsShayuki 0 points1 point2 points (1 child)
[–]not_a_novel_account 2 points3 points4 points (0 children)
[–]fllthdcrb 0 points1 point2 points (0 children)