C/C++ Line Number

C/C++ line number

You should use the preprocessor macro __LINE__ and __FILE__. They are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name.

Others preprocessor variables :

  • __func__ : function name (this is part of C99, not all C++ compilers support it)
  • __DATE__ : a string of form "Mmm dd yyyy"
  • __TIME__ : a string of form "hh:mm:ss"

Your code will be :

if(!Logical)
printf("Not logical value at line number %d in file %s\n", __LINE__, __FILE__);

Get the line number of file

There is no cursor in the context of a standard file stream. There is a file pointer, but not a cursor. The cursor is a concept of the console / terminal driver. Even with file pointers, you don't typically use them in line-mode, they are for random access / binary type access. You can seek to the beginning and end of a file in text mode. But fseek isn't "line or cursor" aware so don't use it.

You simply need to track the number of lines you've read with an integer.

int line = 0;
while((fgets(...)) != NULL) {
line++;
...
if(...) {
// store line number wherever you need it
printf("found at line %d\n", line);
}
}

Is there any way to get the source code line number in C code in run time?

Use gdb instead. But I guess it will work:

  if(someThingsWrong())
printf("wrong at line number %d in file %s\n", __LINE__, __FILE__);

Add line numbers to beginning of every line in a file using C

You have a large number of small problems to address. First, unless you are using a non-conforming compiler, the conforming declarations for main are int main (void) and int main (int argc, char **argv) (which you will see written with the equivalent char *argv[]). See: C11 Standard §5.1.2.2.1 Program startup p1 (draft n1570). See also: What should main() return in C and C++?

Next, c must be type int not type char to match EOF, e.g.

    int c, last = 0; /* c must be type int, not char to match EOF */

Don't hardcode filenames or use magic-numbers. Either pass the filename as an argument to main() or prompt for it within your program. You can conveniently take a filename to open or read from stdin by default with the ternary operator as follows:

    /* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

Finally to your code, since you want to Prefix each line with the line number, you must output the line number for the first line Before you output the characters for that line (and the same for each subsequent line). You can do that simply by outputting the number first (using the "%06zu " conversion specifier with the modifiers '0' to output leading zeros and the field-width 6 to match your format shown). Also note the type for your ln counter is changed from int to size_t, the recommended type for counters in C (you can't have a negative line-count).

Putting this together with the use of the last character to allow checking for the '\n' before outputting your characters, you could do:

#include <stdio.h>

int main (int argc, char **argv) {

int c, last = 0; /* c must be type int, not char to match EOF */
size_t ln = 1; /* use size_t for counters */
/* use filename provided as 1st argument (stdin by default) */
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

if (!fp) { /* validate file open for reading */
perror ("file open failed");
return 1;
}
printf ("%06zu ", ln++); /* output line 1 number */
while ((c = getc(fp)) != EOF) { /* read each character */
if (last) /* test if last set */
putchar (last); /* output all characters */
if (last == '\n') /* test if last is newline */
printf ("%06zu ", ln++); /* output next line number */
last = c; /* set last to c */
}
putchar (last); /* output final character */
if (last != '\n') /* check POSIX eof */
putchar('\n'); /* tidy up with newline */
if (fp != stdin) /* close file if not stdin */
fclose (fp);

return 0;
}

(note: the check of if (last != '\n') after exiting the loop checks for the presence of a POSIX line ending on the last line, and if not, you should manually output a '\n' so that your program is POSIX compliant)

Example Input File

$ cat ../dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

Example Use/Output

$ ./bin/linenos ../dat/captnjack_noeol.txt
000001 This is a tale
000002 Of Captain Jack Sparrow
000003 A Pirate So Brave
000004 On the Seven Seas.

Look things over and let me know if you have further questions.

(also note: if your compiler does not support the zu conversion specifier for size_t, remove the 'z' and output as an unsigned value - VS10 or earlier do not support zu)

C program to print line number in which given string exists in a text file

You cannot read lines with while (fscanf(in_file, "%s", string), the newlines will be consumed by fscanf() preventing you from counting them.

Here is an alternative using fgets():

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

int main() {
char string[200];
char student[100];
int num = 0, line_number = 1;

FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL) {
printf("Error file missing\n");
exit(1);
}
printf("please enter a word \n");
if (scanf("%s", student) != 1) {
printf("No input\n");
exit(1);
}
while (fgets(string, sizeof string, in_file)) {
if (strstr(string, student)) {
printf("line number is: %d\n", line_number);
}
if (strchr(string, '\n')) {
line_number += 1;
}
fclose(in_file);
}
return 0;
}


Related Topics



Leave a reply



Submit