cc.cDenna kod är public domain. Om ni hittar fel eller vill ändra något i koden blir jag jätteglad om ni skickar dessa ändringar till jesper [at] fantasi [punkt] se.
/**
* cc - Char Counter. Finds the n'th character in a file and displays it
* together with some surrounding characters.
*/
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
int ch;
int num;
int pos; /* The character we are looking for */
int sur; /* Number of surrounding characters */
FILE *instream;
/* Check the number of arguments */
if ((argc != 3) && (argc != 4))
{
fprintf(stderr, "Usage: cc filename char# [#surrounding chars]\n");
return EXIT_SUCCESS;
}
/* Read arguments */
if (argc == 4)
sur = atoi(argv[3]);
else
sur = 50;
num = atoi(argv[2]);
if (!(instream = fopen(argv[1], "r")))
{
fprintf(stderr, "Can't open file '%s'\n", argv[1]);
return EXIT_FAILURE;
}
pos = 0;
/* Go through the file character by character */
while ((ch = fgetc(instream)) != EOF)
{
/* The character we are looking for */
if (pos == num)
printf(" >> %c << ", ch);
/* Also print some surrounding characters */
else if (abs(pos - num) < sur)
printf("%c", ch);
pos++;
}
printf("\n");
/* The file was not big enough */
if (num > pos)
fprintf(stderr, "File is not more than %d characters long\n", pos);
/* fclose might fail, but since the program ends here we really
* don't care. */
(void)fclose(instream);
return EXIT_SUCCESS;
}
|