【问题标题】:C program to write last few lines of program, seek error? [closed]C程序写最后几行程序,求错误? [关闭]
【发布时间】:2011-10-08 22:40:43
【问题描述】:

很久以后我试图用c编写代码,程序的目标是 1) 打印作为参数接收的文本文件的最后 10 行。 2) 否则显示错误 seek 命令有问题,在纠正它时丢失了。

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

int main ( int argc, char *argv[] )
{
    char buffer[20],c;
    int bytes =512,flag=0;
    if ( argc != 2 ) /* argc should be 2 for correct execution */
    {
        /* We print argv[0] assuming it is the program name */
        printf( "usage: %s filename", argv[0] );
    }
    else 
    {
        // We assume argv[1] is a filename to open
        FILE *file = fopen( argv[1], "r" );

        /* fopen returns 0, the NULL pointer, on failure */
        if ( file == 0 )
        {
            printf( "Could not open file\n" );
        }
        else 
        {
             while (1)
             {
                   sprintf (buffer, "seek(file,%d,0)", bytes);
                   system(buffer);
                   while ( (c=fgetc(file))!= EOF)
                   {
                         if(c=='\n')
                         {
                              flag++;
                         }
                   }
                   if (flag >= 10)
                      bytes=bytes*2;
                   else 
                        break;
             }

             flag-=10;
             sprintf (buffer, "seek(file,%d,0)", bytes);
             system(buffer);
             while(flag > 0)
             {
                  if((c=fgetc(file))=='\n')
                  {
                         flag--;
                  }
             }
             while ( (c=fgetc(file))!= EOF)
             {
                         printf("%c",c);
             }
        }
    }
}

这是错误,

可运行的程序或批处理文件。 'seek' 未被识别为内部或外部命令, 可运行的程序或批处理文件。

【问题讨论】:

  • 既然您要向操作系统seek(file,%d,0) 发起攻击,它是否在您的路径中,等等。您可以从命令行运行它吗?
  • 这是为了练习C吗?如果您确实需要该功能,请使用tail -n 10。这也是 C++ 还是 C?
  • @therefromhere 这是 c 程序,在某些盒式操作系统上的大部分练习。
  • @AbhilashMuthuraj 好的,所以你不需要 C++ 标签,我会删除它。

标签: c file tail seek


【解决方案1】:

在 C 中,system() 函数接受一个字符串并将其解释为一个 shell 命令(就像您在命令行上键入它一样)。这与“系统调用”不同,后者是对操作系统的低级调用,可能是您在这里感到困惑的根源。

看起来你要使用的是fseek()

fseek(file, bytes, SEEK_SET);

这将取代对sprintfsystem 的调用。

【讨论】:

    【解决方案2】:
    system(buffer);
    

    你实际上是在这样做:cmd seek。所以错误是正确的。 windows默认没有安装seek程序。

    【讨论】:

      【解决方案3】:

      这个系统命令'seek'是什么?你不想用 C 函数 fseek 代替吗?

      【讨论】:

      • fseek 和 seek 命令一样吗?我的意思是语法是一样的?
      • @Abhilash Muthuraj 我们不知道,因为 c 在语言或标准库中没有 seek。无论您使用的是什么seek,都来自操作系统,而您还没有说那是什么(它不是一个POSIX系统,它也没有seek但确实有lseek)。
      猜你喜欢
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多