尝试扫描 C 中用户指定文件中的换行数

Trying to scan the number of newlines in a user designated file in C

我一直在尝试计算名为 testprog 的文件中的换行符数。虽然用户需要输入文件名,但它具有通用性。程序可以编译,但我一直遇到分段错误。

testprog如下

Rd 5000  
st n 2017  
ld zero 1014  
st sum 2016  
L: ld n 1017  
Add sum 3016  
St sum 2016  
Ld n 1017  
Sub one 4015  
St n 2017  
Brgt L 8004  
Ld sum 1016  
Wr 6000  
Stop 0000  
Zero: 0 0000  
One: 1 0001  
Sum: 0 0000  
N: 0 0000  

我的密码是

int main()
{
 unsigned int Line = 0;
 int ch;
 FILE *My_file;
 char command;                              
 //the command being entered

 do
 {
  printf("Command: ");
  scanf("%s",&command);
  if (command=='l'||command=='L')           
  //loads file name to 'memory'
  {
   printf("load file name: "); 
   scanf(" %s",memory);
   My_file = fopen(memory,"r"); 
   while (EOF != (ch=getc(My_file)))
   {
    if ( ch == '\n' )
     Line++;
   }    

输入的命令是L;文件名为 testprog,我在按文件名输入后收到分段错误。我希望接收 17 作为 line 的值,尽管我希望该程序具有通用性,以便稍后使用 testprog2 将正确数量的行发送到 Line。我一直在网上搜索数小时以寻求帮助,但无济于事。非常感谢您提供的任何帮助。

您遇到段错误是因为您试图将非空字符串扫描到单字符变量中:

scanf("%s", &command); // command is char

由于 C 字符串以 null 结尾,您输入的值将写入 command,并且 '[=13=]' 终止符将写入 command 末尾后的位置,导致未定义的行为。

要解决此问题,请创建 command 数组,并为 scanf 提供一个限制,如下所示:

char command[2];
scanf("%1s", command); // %1s tells scanf that the string is at most one-char long

现在您需要使用 command[0] == 代替 command == ... 来解释命令。