将字符打印到文件会产生奇怪的结果
Printing char to file gives weird result
所以我将 char 打印到一个文件中,每当该行结束时它就会做一些奇怪的事情。
这是我使用的代码:
void opdracht43() {
FILE *file;
FILE *file2;
file = fopen("opdracht1.1.cpp", "r");
file2 = fopen("Disc.c", "w");
int p;
char a[100];
while (fgets(a, 100, file)) {
for (int i = 0; i < sizeof a; i++) {
if (a[i] == '\n' || a[i] == ' ' || a[i] == '\t') {
printf("TRUE");
}
else {
printf("FALSE");
fputc(a[i], file2);
}
}
return 0; //So it only prints the 1st line for now.
}
fclose(file);
fclose(file2);
}
当它运行时,这是它给出的文本:
#include<stdio.h> ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ
> 和 Ì 之间的 space 在记事本++中给我一个奇怪的黑色 nul
文件的第一行是:
#include<stdio.h>
希望能在这里找到一些帮助:)
sizeof a
是变量 a
的大小(以字节为单位),它始终为 100。您想用 a
中保存的字符串的长度来限制循环,这是 strlen(a)
。
此外,您不应该逐个字符地写入文件流。这不是文件 I/O 设计的工作方式。
改变
for (int i = 0; i < sizeof a; i++) {
到
for (int i = 0; a[i] != '[=11=]' && i < sizeof a; i++) {
在你的例子中,在 fgets()
的第一次调用中给数组 a
这些值:'#'、'i'、'n'、'c' , ..., 'o', '.', 'h', '>' 和一个 '\0'。但是,a
的其余部分仍然包含像 Ì
这样的垃圾,因为 a
从未被初始化。
'\0' 就是您提到的 "weird black nul"。 '\0' 是 C 风格字符串结束的标志,但它不代表文件的结束,因此不应将其写入 "Disc.c" 使用 fputc()
所以我将 char 打印到一个文件中,每当该行结束时它就会做一些奇怪的事情。
这是我使用的代码:
void opdracht43() {
FILE *file;
FILE *file2;
file = fopen("opdracht1.1.cpp", "r");
file2 = fopen("Disc.c", "w");
int p;
char a[100];
while (fgets(a, 100, file)) {
for (int i = 0; i < sizeof a; i++) {
if (a[i] == '\n' || a[i] == ' ' || a[i] == '\t') {
printf("TRUE");
}
else {
printf("FALSE");
fputc(a[i], file2);
}
}
return 0; //So it only prints the 1st line for now.
}
fclose(file);
fclose(file2);
}
当它运行时,这是它给出的文本:
#include<stdio.h> ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ
> 和 Ì 之间的 space 在记事本++中给我一个奇怪的黑色 nul
文件的第一行是:
#include<stdio.h>
希望能在这里找到一些帮助:)
sizeof a
是变量 a
的大小(以字节为单位),它始终为 100。您想用 a
中保存的字符串的长度来限制循环,这是 strlen(a)
。
此外,您不应该逐个字符地写入文件流。这不是文件 I/O 设计的工作方式。
改变
for (int i = 0; i < sizeof a; i++) {
到
for (int i = 0; a[i] != '[=11=]' && i < sizeof a; i++) {
在你的例子中,在 fgets()
的第一次调用中给数组 a
这些值:'#'、'i'、'n'、'c' , ..., 'o', '.', 'h', '>' 和一个 '\0'。但是,a
的其余部分仍然包含像 Ì
这样的垃圾,因为 a
从未被初始化。
'\0' 就是您提到的 "weird black nul"。 '\0' 是 C 风格字符串结束的标志,但它不代表文件的结束,因此不应将其写入 "Disc.c" 使用 fputc()