c - 如何从文本文件中读取值并将它们存储在 C 中的不同变量类型中

标签 c file

我需要将一个包含 7 行的文本文件读取到 7 个不同的变量中。文本文件如下所示:

.2661
A.txt
B.txt
C.txt
1
2
0.5 0.6 

这些是我需要将每一行存储到的变量:

float value1;             // line 1 from .txt file
char *AFileName;          // line 2 from .txt file
char *BFileName;          // line 3 from .txt file
char *CFileName;          // line 4 from .txt file
int value2;               // line 5 from .txt file
int lastLineLength;       // line 6 from .txt file
double lastLine[lastLineLength];    // line 7 from .txt file - this can be different lengths

当前,当我从命令行和 argv 命令调用程序时,我仅使用参数来执行此操作。

最佳答案

首先使用具有读取权限的 fopen 打开文件:

FILE *inputFile = fopen(filename, "r");
if(!inputFile) {
    // Error opening file, handle it appropriately.
}

然后使用fscanf从文件中读取数据。第一个参数是我们上面创建的FILE *。第二个参数是一个格式字符串,指定读取文件时 fscanf 应该期望什么。其余参数是指向变量的指针,这些变量将保存从文件中读取的数据。

int variablesFound;
variablesFound = fscanf(inputFile, "%f\n%s\n%s\n%s\n%d\n%d\n", &value1, AFileName, BFileName, CFileName, &value2, &lastLineLength);
if(variablesFound < 6) {
    // There was an error matching the file contents with the expected pattern, handle appropriately.
}

double lastLine[lastLineLength];

// Iterate over the last line.
int lastLineIndex;
for(lastLineIndex = 0; lastLineIndex < lastLineLength; lastLineIndex++) {
    fscanf(inputFile, "%lf", &lastLine[lastLineIndex]);
    fscanf(inputFile, " ");  // Eat the space after the double.
}

编辑

发表评论后,我意识到可能值得注意的是,您必须为变量分配内存作为真正的第一步。原语(下面带有 & 的原语)可以正常声明。对于字符串(字符数组),您需要执行以下操作之一:

char *aFileName = calloc(MAX_FILENAME_SIZE + 1, sizeof(char));

char aFileName[MAX_FILENAME_SIZE + 1];

根据您使用 aFileName 的目的,确定哪种方法合适。但是,假设此代码出现在 main 中或者不需要存在于函数范围之外,则后者会更好,因为它不需要 free() 使用完变量后对其进行处理。

如果您的需求经常发生变化,那么挑选出处理读取输入的代码也可能是值得的。

关于c - 如何从文本文件中读取值并将它们存储在 C 中的不同变量类型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42631266/

相关文章:

C 数组数组

c - return(NULL) 中多余括号的目的是什么

java - 文件中的扫描仪输入不匹配异常

python - 在 ZipFile 中保留文件属性

c - 错误 : assignment makes integer from pointer without a cast (using gets)

c - 这个 Makefile 有什么问题?

c - exec() 输出重定向时的奇怪行为

java - 我如何知道哪些进程正在使用 Windows 中 Java 下的文件?

java - 通过Java套接字发送多个文件

python - 如何从外部文件中列出 python 中的数字?