C程序卡住,甚至没有进入主程序

Man*_*M J 1 c gcc runtime-error

我为FCFS调度编写了以下代码.问题是这段代码编译正常,但执行后./a.out,没有显示任何内容,程序卡住了.它甚至没有"Reading" printf在开头打印声明main().问题是什么?

#include <stdio.h>

struct process
{

  int at;
  int bt;
  int wt;
  int tt;
  int rt;
  char pid[5];

} p[5];

int i, j;
int n = 0;

void main()
{
  printf("Reading");
  FILE *fp;
  fp = fopen("in1.txt", "r");
  char sample;
  if (fp != NULL )
  {
    sample = getc(fp);
    while (sample != EOF);
    {
      if (sample == '\n')
        n++;
      sample = getc(fp);
    }
    fseek(fp, 0, 0);
    for (i = 0; i < n; i++)
    {
      fscanf(fp, "%s %d %d", p[i].pid, &p[i].at, &p[i].bt);
      p[i].wt = p[i].tt = 0;
      p[i].rt = p[i].bt;
    }
    fclose(fp);
  }
  //sorta();
  printf("\nGantt Chart for FCFS\n");

  int t = 0;
  int avgw = 0;
  int avgt = 0;
  printf("%d ", t);
  for (i = 0; i < n; i++)
  {
    if (p[i].at > t)
    {
      printf("%d ", t);
      t = p[i].at;
    }
    p[i].wt = t - p[i].at;
    avgw = avgw + p[i].wt;
    printf("%s ", p[i].pid);
    p[i].tt = p[i].bt + p[i].wt;
    avgt = avgt + p[i].tt;
    t = t + p[i].bt;
    printf("%d ", t);
    printf("\navg waiting time = %d", avgw / n);
    printf("\navg turn around time = %d", avgt / n);
  }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*thy 8

标准输出是行缓冲的.将"阅读"改为"阅读\n",你会看到它.

那你在这里犯了一个错误:

while (sample!=EOF);
Run Code Online (Sandbox Code Playgroud)

那个while循环的主体只是分号,而不是之后的块!如果条件为真,则程序将陷入无限循环.

  • @Lundin:阙?EOF保证为负值(ISO/IEC 9899:2011§7.21.1:'`EOF` [...]扩展为整数常量表达式,类型为"int",负值为"".你是对的``getc()`返回一个`int`,但循环终止取决于普通`char`是有符号还是无符号.如果有符号,则字符代码0xFF(ÿ)将过早触发EOF; 如果它是无符号的,那么你有一个无限循环,因为没有unsigned char值等于-1. (2认同)