简体   繁体   English

C-我的程序从文件读取后打印出奇怪的东西

[英]C - my program prints weird stuff after reading from a file

I am trying to make a program for an assignment to read ID3 tags. 我正在尝试编写一个分配ID3标签的程序。 I don't have much code so far because I'm trying to learn how to work with the ID3 tags themselves. 到目前为止,我没有多少代码,因为我正在尝试学习如何使用ID3标签本身。 I made a little program which would read the first three letters and just print them back, just to see how the process of opening the file and closing it would work, etc. 我编写了一个小程序,将读取前三个字母并将其打印回去,以了解打开文件和关闭文件的过程如何工作,等等。

This is my code: 这是我的代码:

#include <stdio.h>

int main(int argc, char *argv[]) {

  char buf[4];

  if (argc == 2) {
    FILE *mp3 = fopen(argv[1], "r");

    fread(buf, 3, 1, mp3);
    buf[3] = "\0";
    printf("%s\n", buf);
    fclose(mp3);
    char a = buf[0];
    char b = buf[1];
    char c = buf[2];
    printf("%x\t%x\t%x\n", a, b, c);
  }
  return 0;
}

It manages to print what is it supposed to (ID3) but then it makes some weird letters appear after the ID3 part. 它设法打印出预期的内容(ID3),但随后使一些奇怪的字母出现在ID3部分之后。 I added a part to print the hex values of those as well. 我还添加了一个部分来打印这些内容的十六进制值。

I am new to C and I find this very difficult to understand. 我是C语言的新手,我很难理解这一点。 Also, I don't quite understand the differences between all the different ways of making and managing a string. 另外,我不太了解制作和管理字符串的所有不同方式之间的区别。 So I would greatly appreciate any help regarding this and how to make it better and explain to me why etc. 因此,我非常感谢您对此提供的任何帮助以及如何使其变得更好并向我解释原因等。

The part where you assign "\\0" to buf[3] is wrong. 您为buf [3]分配“ \\ 0”的部分是错误的。 You should use single quotes: 您应该使用单引号:

buf[3] = '\0';

The reason is that double quotes means a string literal (which is a null terminated char array) and not a char variable. 原因是双引号表示字符串文字(以null终止的char数组),而不是char变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM