C语言: Search text file for a "word" and store the value into int and flout type variables

标签 c scanf fgets

例如文本文件(vars.txt)包含:

var1
10
var2
3.54
var3
10110

我想读取文本文件并将 var1 的值(文本文件中 var1 之后的下一行)存储到程序中的变量中。 我有以下代码,但似乎不起作用:

char cBuffer[256];
FILE *pSrcFile;
pSrcFile = fopen("vars.txt","r");
while( (fgets( cBuffer, 256 , pSrcFile)) != NULL )
{
    if( strcmp( cBuffer, "var1" ) != NULL )
    {
        sscanf( pSrcFile, "%d" , &var1 );
        printf("var1 is found= %d",var1);
        break;
    }
}

如何将文本文件的字符串转换并保存为 int、flout 和 bin 类型变量?

换句话说,我想搜索文本文件以找到“var1”,然后将下一行(“var1”的值)保存到整数变量中,并重复此操作以搜索并存储“var2”的值转换为浮点变量,“var3”转换为二进制变量等等。

最佳答案

这是如何读取、写入文件的示例: //读取:

FILE *f1, *f2;
f1 = fopen("IN.INP","r");
fscanf(f1,"%d",&vars);    
fclose(f1);
//Write:
f2 = fopen("OUT.OUT", "w");
fprintf(f2, "%d",vars);
fclose(f2);

我不确定我是否正确理解您的问题“如何将 .txt 转换为 int、float、binary 类型变量”。但具体方法如下:

char a = 10;
int b = (int) a;

但是,如果您只想将 .txt 的值读入 int、float 中,那么只需使用 fscanf(f1,"%d",&vars);//d 为 int

关于C语言: Search text file for a "word" and store the value into int and flout type variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53740841/

相关文章:

c - 如何在字符串中显示字符\t?

c - 程序不会打印 txt 文件中的所有行

c - 从用户那里获取字符串的更好方法

c - 如何在C语言中将文本文件读取到结构数组中

c - C中链表的总大小

c - 头文件中声明的外部变量的链接器出错

c - fscanf - 如何处理两个 float +空格+换行符?

c++ - 带信号的 Scanf

c - 函数中 fgets 的格式化问题

c - 解析char数据时出现Segmentation fault (core dumped)