Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Stuck with an excersize

IsoDeathscarIsoDeathscar Member Posts: 1
[b][red]This message was edited by the IsoDeathscar at 2002-7-1 15:44:16[/red][/b][hr]
Hi guys, I'm stuck with a linux c programming excersize,My proggie should work but it isn't:(, here's the excersize.

Exercise 12577

Write a program last that prints the last n lines of a text file, by n and the file name should be specified form command line input. By default n should be 5, but your program should allow an optional argument so that


last -n file.txt

prints out the last n lines, where n is any integer. Your program should make the best use of available storage.




ANd here is my code,
// Made by IsoDeathcar
#include
#include
int main(int argc, char *argv[])
{
FILE *stream;
char *buffer;
char string[255];
int lines;
int i;
if (argc == 1)
{
fprintf(stderr,"Specify a file to read %s file
",argv[0]);
exit (1);
}

if (argc == 2)
{
argv[1];
lines = 5;
}

if (argc == 3)
{
lines = 0-atoi(argv[1]);
strcpy(string, argv[2]);
}

buffer = (char*)malloc(lines*255*sizeof(char));
stream = fopen(string,"r");

while(!feof(stream))
{
for(i=0;i<lines-1;i++)
{
strncpy(buffer+(255*i), buffer+(255*(i+1)), 255);
}
fgets(buffer+(255*lines-1), 255, stream);
}


for (i=0;i<lines;i++)
{
printf("%s",buffer+(255*i));
}

return 0;
}

I just keep getting a segmentation error and I've tried a lot of things, but still get tthe same error, can somone please help me out.
thnks.


Comments

  • Shawn CarterShawn Carter Member Posts: 0

    __ | http://forcoder.org | free video tutorials and ebooks about { Objective-C JavaScript PHP Java Swift C++ Scratch Go C Assembly Python Perl Delphi R PL/SQL Visual Basic .NET Ruby MATLAB C# Visual Basic Lisp FoxPro Crystal Erlang Dart VBScript SAS Logo Hack ABAP Scala Kotlin COBOL Rust F# Clojure ML Lua LabVIEW D Transact-SQL Fortran Julia Alice Awk Ada Prolog Scheme Apex Bash } __________

Sign In or Register to comment.