【问题标题】:Writing and reading from a file and sort them in ascending order写入和读取文件并按升序排序
【发布时间】:2013-09-03 15:42:04
【问题描述】:
#include<stdio.h>
void sort(int *p, int size)
{
  int i, j;
  for (i = 0; i < size - 1; ++i)
  {
    for (j = 0; j < size - i - 1; ++j)
    {
      if (p[j] > p[j + 1])
      {
        int temp;
        temp = p[j];
        p[j] = p[j + 1];
        p[j + 1] = temp;
      }
    }
  }
}

void createtestfile()
{
  FILE *f1;
  f1 = fopen("program.txt", "w");
  fprintf(f1, "6#this is comment\n");
  fprintf(f1, "3#this is comment\n");
  fprintf(f1, "7#this is comment\n");
  fprintf(f1, "2\n");
}

void readtestfile()
{
  FILE *fp;
  char buff[1024];
  int value;

  int number_of_lines;
  fp = fopen("program.txt", "r");
  do
  {
    fgets(buff, 1024, fp);
    fscanf(fp, "%d", &value);
    number_of_lines++;
    buff[number_of_lines] = value;
  } while (fp != EOF);

  sort(buff, number_of_lines);

  int i;
  for (i = 1; i < number_of_lines; i++)
  {
    printf("value is %d", buff[i]);
  }
}

int main()
{
  createtestfile();
  readtestfile();
  return 0;
}

我正在将字符串写入文件。稍后仅从文件中读取整数并按升序对它们进行排序。我正在使用 fgets 从文件中逐行读取,并且在从文件中仅读取整数时遇到问题。

【问题讨论】:

  • 输出:它没有显示任何数字。

标签: c file-io fgets scanf bubble-sort


【解决方案1】:

您在写入文件后无法关闭该文件。

因此,最有可能在应用程序结束时写入内容,因为到那时将被隐式关闭。

添加

fclose(f1) 

createtestfile() 中的最后一个fprintf() 之后。


其次,从文件中读取数据时,您应该决定是否使用fscanf()fgets() 来读取数据。

或者您可以从使用fscanf() 直接从文件读取切换为从使用fgets() 读取的“字符串”中执行sscanf()

为此替换

fscanf(fp, "%d", &value);

sscanf(buff, "%d", &value);

第三,尝试将您从buff 扫描的内容写回buff 是没有意义的,至少因为您在下一轮读取循环中覆盖了buff

您还将buff 传递给sort(),这应该会让编译器大声发出警告。

将循环计数器number_of_lines 正确初始化为0,并使用整数数组存储您从文件内容中扫描出来的值。然后您可以将其传递给sort()

【讨论】:

  • 我在 readtestfile() 和 createtestfile() 中都关闭了,但它也没有显示任何输出。
【解决方案2】:

fgets 是消费线,你必须在fgets 之后使用sscanf 而不是fscanf

  do
  {
    fgets(buff, 1024, fp);
    fscanf(fp, "%d", &value); /* here */

【讨论】:

    【解决方案3】:

    仅据您所知,您可以使用内置的排序函数 qsort 对数据进行排序。

    这是一个例子:

    #include <stdio.h>      /* printf */
    #include <stdlib.h>     /* qsort */
    
    int values[] = { 40, 10, 100, 90, 20, 25 };
    
    int compare (const void * a, const void * b)
    {
      return ( *(int*)a - *(int*)b );
    }
    
    int main ()
    {
      int n;
      qsort (values, 6, sizeof(int), compare);
      for (n=0; n<6; n++)
         printf ("%d ",values[n]);
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 2021-10-31
      • 2021-09-21
      • 2011-07-13
      • 1970-01-01
      • 2018-11-20
      相关资源
      最近更新 更多