So I need to open/read a file and find the number of lines that DO NOT contain the symbol |
. However, I can't get this to work with strchr()
like this:
#include <stdio.h>
#include <stdlib.h>
int countLOC(FILE *filename){
int c, nlines = 0;
filename = fopen(filename, "r");
while (c != EOF){
if (c == '\n' && strchr(c,'|') != NULL)
nlines++;
c = getc(filename);
}
printf("%d",nlines);
}
int main(){
countLOC("charc.c");
return 0;
}
The program crashes and I have no idea why. Initially, the code would just count all lines (except blank lines) but I need to check if each line contains a |
.
You cannot pass a character to strchr()
, it takes a pointer to char
. If you enable compiler warnings, you would have known this.
If you want to count the lines with your current code, you should read each character until a '\\n'
is found, keep a flag to know if there was one of occurance ot the searc character in the line, then if at least on character matched the search character, you count a line otherwise you don't, and reset the flag.
Also the line
filename = fopen(filename, "r");
is wrong, because fopen()
returns a FILE *
object, it's an I/O stream which you can use to read from the file.
You have other mistakes too, see this code. Hope you notice what where the other mistakes
#include <stdio.h>
#include <stdlib.h>
int countLOC(const char *const filename)
{
int c, nlines = 0;
int found = 0;
FILE *file;
file = fopen(filename, "r");
if (file == NULL)
{
printf("failed to open %s\n", filename);
return -1;
}
while ((c = fgetc(file)) != EOF)
{
if (c == '\n')
{
nlines += (found != 0) ? 1 : 0;
found = 0;
}
found = ((c == '|') || (found != 0));
}
nlines += (found != 0) ? 1 : 0;
printf("%d", nlines);
fclose(files);
return nlines;
}
int main()
{
countLOC("charc.c");
return 0;
}
int countLOC(const char *filename){
int c, nlines = 0, hasCh = 0;
FILE *fp = fopen(filename, "r");
while(1){
c = getc(fp);
if (c == EOF || c == '\n'){
if(hasCh)
nlines++;
if(c == EOF)
break;
hasCh = 0;
} else if(!hasCh && c == '|'){
hasCh = 1;
}
}
fclose(fp);
printf("%d\n",nlines);
return nlines;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.