-4

很长一段时间后,我试图用 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' 不是内部或外部命令、可运行程序或批处理文件。

4

3 回答 3

3

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

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

fseek(file, bytes, SEEK_SET);

sprintf这将取代对和的调用system

于 2011-10-08T23:06:11.287 回答
1
system(buffer);

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

于 2011-10-08T22:44:13.717 回答
0

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

于 2011-10-08T22:43:45.340 回答