I'm new to programming and I have a program which runs but I need to display line numbers for it. Could I used the C macro __LINE__
? If so where could I insert it in the code and if not what could I do in order for the program to print out line numbers along with the code? Thanks in advance.
Asked
Active
Viewed 1.1k times
0
1 Answers
1
The __LINE__
macro expands into an integral line number (the presumed line number within the source file) so you can pretty well use it anywhere an integer is usable:
printf ("This line is %d.\n", __LINE__);
From C11 6.10.8.1 Mandatory macros
:
__LINE__
The presumed line number (within the current source file) of the current source line (an integer constant).
If, as may be the case based on your comments, you need simply have a program that outputs itself with line numbers, I'd suggest not using __LINE__
for that.
Instead, it would probably be better to have the program keep a record of which line it's on, and output that before the line itself. See, for example:
#include <stdio.h>
int main (void) {
static char buff[100000];
int lineNum = 0;
FILE *fp = fopen (__FILE__, "r");
if (fp != NULL) {
while (fgets (buff, sizeof (buff), fp) != NULL) {
printf ("%7d: %s", ++lineNum, buff);
}
fclose (fp);
}
return 0;
}

paxdiablo
- 854,327
- 234
- 1,573
- 1,953
-
Sorry if this sounds dumb but would I need to insert that once into the code or right before each line? – mishi Apr 09 '15 at 04:34
-
@mishi, you would need to insert it everywhere you wanted the line number printed out. Doing it before every line of code would be a fair bit of work so you may need to step back and tell us the actual problem you're trying to solve. It's likely there's a better way. – paxdiablo Apr 09 '15 at 04:35
-
i made a program that reads its own source file and now i need to open another text file with the same source file but include line numbers in the text file – mishi Apr 09 '15 at 04:41
-
@mishi, in that case, I'd simply modify the program to keep a count of what line it's on and output that before the line itself. That's going to be a lot easier than trying to use `__LINE__`. – paxdiablo Apr 09 '15 at 04:52