[英]how to find in which line the string is in csv file in c
我需要檢測字符串在 c 中的 csv 文件中的哪一行 .. 我嘗試計算 '\\n' 次,直到我們到達我們的字符串位置......但它總是打印在第二行,無論如何是輸入。 它就像它沒有真正讀取文件並將文本復制到 buff 字符串......而且 strcpsn 也不起作用
printf("\nEnter the string you want to search: ");
getchar();
myFgets(str, LEN); //getting input
file = fopen(adr, "r"); //opening file
if (file == NULL)
{
printf("Eror opening first file\n");
return 1;
}
fseek(file, 0, SEEK_END);
len = ftell(file);
fseek(file, 0, SEEK_SET);
char* buff = (char*)calloc(strlen(str), sizeof(char));
if (buff == NULL)
{
printf("Allocation eror!\n");
return 1;
}
fread(buff, sizeof(char), len, file);
seek = strcspn(buff, str); //checking where is the string starting
while (lineSeek <= seek)
{
ch = fgetc(file);
if (ch == '\n')
{
line++;
lineSeek = ftell(file);
}
}
printf("its on %d line", line + 1);
你可能使它變得比它需要的更難。 您可以使用strstr
搜索每一行,因為它是為您的搜索詞讀取的。 您可以在增加行數之前使用strchr
確認該行包含'\\n'
(以防止使用fgets
進行短讀。
把它們放在一起,所有需要的是以下內容。 請注意,代碼將搜索詞作為第一個參數,然后將要搜索的文件名作為第二個參數(如果沒有給出第二個參數,它將默認從stdin
讀取):
#include <stdio.h>
#include <string.h>
enum { MAXC = 512 };
int main (int argc, char **argv) {
if (argc < 2 ) {
fprintf (stderr, "insufficient input, usage: %s term [file (stdin)]\n",
argv[0]);
return 1;
}
size_t found = 0, line = 0;
char buf[MAXC] = "";
char *term = argv[1];
FILE *fp = argc > 2 ? fopen (argv[2], "r") : stdin;
if (!fp) {
fprintf (stderr, "error: file open failed '%s'.\n", argv[2]);
return 1;
}
while (fgets (buf, MAXC, fp)) { /* read each line */
if (strstr (buf, term)) { /* test for term */
found = 1; break; /* set found flag */
}
if (strchr (buf, '\n')) line++; /* increment line */
}
if (fp != stdin) fclose (fp);
if (found) printf ("'%s' found on line %zu.\n", term, line + 1);
return 0;
}
注意:如果你想匹配整個字段,你可以在將每個標記與搜索詞進行比較之前用strsep
標記每一行。 如果空字段不是問題,則可以使用strtok
。
示例輸入
$ cat dat/search.csv
my,dog,has,fleas
the,other,one,doesn't
the,cat,has,none
the,snake,is,done
示例使用/輸出
$ ./bin/searchcsv cat <dat/search.csv
'cat' found on line 3.
看看它,如果您有任何問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.