c - 从文件中的特定点读取一行

标签 c printf malloc scanf

所以我正在编写代码来获取 scanf 文本文件并返回格式文本消息日志。我想知道如何在某个点扫描文件中的字符串并打印该点之外的每个字符串 E.X 当文件扫描该行时 “332982000 2055552002 2055551001 7 韦伯先生,我可以问你一个问题吗?”我将前 4 个数字扫描为整数,并将其余的书面文本扫描到从“Mr. Webb”开始的字符数组中。

我尝试使用 for 循环和 fscanf 来扫描数组,但没有成功。我还想我可以使用 malloc 只是为了节省空间,但我不知道在 sizeof 参数中放入什么。任何帮助将不胜感激!

int posix;
int phone1;
int phone2;
int textsize;
int val, val2;
char line[256];
char text[3000];
int len=strlen(line);
int i=0;

printf("\n\nTime                           %s                           %s", argv[2], argv[3]);
printf("\n======================================================================================\n\n\n");

FILE* textfile= fopen(argv[1],"r");

fscanf(textfile, "%d %d %d %d %s", &posix, &phone1, &phone2, &textsize, text);

while( fgets(line, sizeof(line), textfile) ) { 

    val= atoi(argv[2]);
    val2=atoi(argv[3]);

    if ( (val==phone1) && (val2==phone2) ) {
        printf(" %s ", text); //only prints Mr
        text=(char*)malloc(sizeof())//tried malloc but not too sure how to use it correctly
        for (i=0; i<len; i++) { //tried using for loop here didnt work. 
          fscanf("%s", text);
          }

        sortText(phone1, phone2, textsize, text);
        //readableTime(posix);
         }

else if ( (val2==phone1) && (val==phone2) ) { printf("%s ", 文本);

        sortText(phone1, phone2, textsize, text);
        //readableTime(posix);
         }


fscanf(textfile, "%d %d %d %d %s", &posix, &phone1, &phone2, &textsize, text);             

}

fclose(textfile);
return 0;

}

最佳答案

首先,将整个文件读入 malloc 的字符数组中。 fseek 和 ftell 为您提供文件大小:

// C99
FILE *fp = fopen("file", "r");
size_t filesize;
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *filetext = malloc(filesize + 1);
fread(filetext, 1, filesize, fp);
filetext[filesize] = 0;

然后使用整个文件大小的单行缓冲区,这样您就肯定有足够的大小。 sscanf() 可用于从字符串中读取内容。

int readbytes;

for(int i=0; i < filesize; i+=readbytes) {
    char line[filesize];
    int posix, phone1, phone2, textsize;

    if(EOF == sscanf(
        &filetext[i], "%d%d%d%d%[^\n]%n", &posix, &phone1,
        &phone2, &textsize, line, &readbytes))
    {
        break;
    }

    printf("%d %d %d %d '%s' %d\n", posix, phone1, phone2, textsize, line, readbytes);
}

格式说明符“%[^\n]”表示:直到下一个换行符的每个字符。格式说明符“%n”为您提供迄今为止通过此 sscanf 调用读取的字节数,实际上是您的行大小,您可以使用它来推进迭代器。

关于c - 从文件中的特定点读取一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42519194/

相关文章:

检查给定数字是否是 2 个数组中两个数字的总和

c - c11 _Generic 通用关联的结果表达式的每个分支是否都必须有效?

c - 为什么我的浮点值不能正确打印?

c - 为什么我的指针数组在动态分配后被覆盖?

c - SECCOMP:如何模拟 malloc、realloc 和 free?

检查 time_t 变量是否已初始化

c++ - 外部 "C"或不外部 "C"[g++ vs cl]

c - write vs fprintf - 为什么不同,哪个更好?

C printf 函数无法正确对齐包含土耳其字符的字符串

c - malloc的返回值是虚拟地址还是物理地址?