【问题标题】:How to solve bugs with files in C如何解决 C 中文件的错误
【发布时间】:2021-09-15 17:28:18
【问题描述】:

我是一名 C 学习者,我在使用 C 中的文件时遇到了很大的困难。每次我尝试用文件在 C 中制作一个小程序时,比如在一个简单的 txt 上打印一些数据,它总是会打印垃圾字符和/或忽略一些上述数据。即使我从 stackoverflow.com 或 Deitel 教科书中完全复制了一段可能正常运行的代码,它也永远无法正常工作。 这是我一直在尝试的代码示例:

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

// a struct to read and write
struct person 
{
int id;
char fname[20];
char lname[20];
};

int main ()
{
FILE *outfile;
  
// open file for writing
outfile = fopen ("person.dat", "w");
if (outfile == NULL)
{
    fprintf(stderr, "\nError opend file\n");
    exit (1);
}

struct person input1 = {1, "rohan", "sharma"};
struct person input2 = {2, "mahendra", "dhoni"};
  
// write struct to file
fwrite (&input1, sizeof(struct person), 1, outfile);
fwrite (&input2, sizeof(struct person), 1, outfile);
  
if(fwrite != 0) 
    printf("contents to file written successfully !\n");
else 
    printf("error writing file !\n");

// close file
fclose (outfile);

return 0;
}

这是一个简单的代码,应该在 dat 上写一些东西。文件。 在这种情况下,它不会打印数字,只会打印一个小矩形,并且会打印不带换行符的名称。但我见过最糟糕的情况,因为许多其他代码只会打印出许多垃圾字符。我正在使用代码块。此外,我注意到在我只使用 fprintf、fscanf 和简单变量而不是结构之前,一切似乎都有效。其他任何事情都会使代码做一些奇怪的事情。请帮忙:(

【问题讨论】:

  • if(fwrite != 0) 不会像您认为的那样做。请退后几步,拿起一本初学者的 C 书阅读有关文件以及如何使用the fwrite function.
  • 数字是存储二进制,所以文本编辑器不会显示它们。如果您使用结构读取文件,它应该可以工作。
  • 程序的输出在作为字节转储查看时很好,但在文本编辑器中则不行。问题似乎在于您对结果应该是什么的想法,以及格式化的二进制文件和文本文件之间的区别。
  • 文件名没有区别。它只提示文件的内容。 “名称没有换行符”的原因是因为 struct 数据中没有任何内容,并且您没有明确写入文件。在int num = 42; 这个fwrite(&amp;num, sizeof num, 1, outfile); 和这个fprintf(outfile, "%d", num); 之后做完全不同的事情。
  • 请在问题中解释“不起作用”是什么意思。使用文本编辑器查看fwrite(&amp;num, sizeof num, 1, outfile); 编写的文件内容不会显示任何有用的信息,因为数据输出不是文本。输出文件的名称是“test.txt”还是“test.dat”都没有关系

标签: c file debugging struct


【解决方案1】:

正如 cmets 中的其他人所指出的,fwrite 将以二进制而不是文本输出。如果您需要以文本形式输出,您或许应该创建一个print_person 函数,如下所示:

int print_person(struct person *p, FILE *fp) {
    return fprintf(fp,"%d\n%s\n%s\n",p->id,p->fname,p->lname);
}

然后在你的main 中,这样称呼它:

if (print_person(&input1,outfile) < 0) {
    printf("Error writing to file\n");
    exit(-1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    相关资源
    最近更新 更多