【问题标题】:Read - Write Txt File in C读取 - 在 C 中写入 Txt 文件
【发布时间】:2016-12-17 12:16:31
【问题描述】:

我正在尝试读取 - 写入一个 txt 文件,该文件在不同的行中有多个信息。 它的形式是:

Number-LicencePlate NumberOfSeats

Name  number  phonenumber

Name  number  phonenumber

Name  number  phonenumber

使用 fscanf 很容易阅读第一行 但是如何使用 fscanf 读取其余部分以获得 3 个不同的变量(姓名、号码、电话)?

稍后会以相同的形式写入此文件,但会尝试解决..

FILE *bus;
bus = fopen ("bus.txt","r");
if (bus == NULL)
{
    printf("Error Opening File, check if file bus.txt is present");
    exit(1);
}
fscanf(bus,"%s %d",platenr, &numberofseats); 
printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats);

【问题讨论】:

  • 这里有大量重复项:google.com/…
  • 使用while循环!
  • 我可以使用 while 循环,但是如何跳过第一行来循环文件的其余部分?我发现可以这样做: fscanf(config_file, "%*[^\n]\n", NULL);
  • 写好错误信息:char *path = "bus.txt"; bus = fopen(path, "r"); if(bus==NULL){ perror(path); exit(1);} 系统错误很重要(文件不存在,还是权限问题?不要让用户猜测,告诉他们)并且属于标准错误。

标签: c text-files scanf


【解决方案1】:

您应该使用循环来实现您正在寻找的内容,因为您的代码除了第一行之外不读取任何内容,因为"FILE *bus;" 是指向文本文件第一行的指针。

为了阅读所有内容,您可以通过检查文件结束 (EOF) 来使用简单的 while 循环。我知道有两种方法,它们在这里;

  while(!feof(bus)){
       fscanf(bus,"%s %d",platenr, &numberofseats);
       printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats);
    }

此代码块将在读取后打印每一行。 我们使用了“feof (FILE * stream);”函数Learn More Here。其他文章上也有建议的替代方法How to read a whole text file

但我也会把它放在这里。

  while(fscanf(bus,"%s %d",platenr, &numberofseats)!=EOF){
        printf("Bus Licence plate Nr is: %s and number of seats is: %d", platenr, numberofseats);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2013-03-25
    • 2023-03-22
    • 2020-03-06
    相关资源
    最近更新 更多