如何读取外部文件,然后打印整个文本或选定的行?
FILE *fp;
fp=fopen("c:\\students.txt", "r");
我理解读取文件但在此之后我迷路了。请帮助!!!
我需要读二进制文件还是文本文件?
答案 0 :(得分:0)
fopen()
fread()
只会返回该程序实际数据的数量
可以在.txt文件中找到 - 这是非常误导的。主要用途是为循环获取元素数。如果您确切知道该文件应该具有什么,您可以将文件上传到您的程序中,并在屏幕上打印而不必触及此功能。如果您不知道文件中的内容,请仅使用此选项。 getline()
是您打印特定行的首选。没办法绕过这个,你需要特定的库。 这是我在对此进行自学时编写的示例代码,只是展示了如何使用这些代码,并打印出 BOTH 程序,以及程序外的单独txt文件。但它没有getline()
。
/*
Goals:
Create an array of 5 values
Input 5 vales from a pre-created file, into the new array
Print out the 5 values into another file.
Close the file.
*/
#include <stdio.h>
#include <stdlib.h>
#define DATAFILE "E:/Data.txt"
#define REPORT "E:/Report.txt"
//prototypes
FILE *Open_File();
void Consolodate_Array(int a_array[], FILE *file_pointer);
void Print_File(int a_array[], FILE *report_pointer);
void end_function(FILE *file_pointer, FILE *report_pointer);
int main(int argc, char *argv[])
{
int array[5];
FILE *Datatext = Open_File();
//Declared "Datatext" to be equal to Open_File's Return value.
//FILE itself is like Int, Double, Float, ect.
FILE *ReportText = fopen(REPORT, "w");
//Did the same as above, just not in a separate function. This gives us a
//Pointer to the REPORT.txt file, in write mode instead of read mode.
Consolodate_Array(array, Datatext);
Print_File(array, ReportText);
end_function(Datatext, ReportText);
system("PAUSE");
return 0;
}
/*----------------------------------------------------------------------*/
//This function should open the file and pass a pointer
FILE *Open_File()
{
return fopen(DATAFILE, "rb");
}
/*----------------------------------------------------------------------*/
//This function should input the variables gotten for the file, into the array
void Consolodate_Array(int a_array[], FILE *file_pointer)
{
for(int i=0; i<5; i++)
fscanf(file_pointer, "%i", &a_array[i]);
}
/*----------------------------------------------------------------------*/
//This function prints out the values into the second file, & at us too.
void Print_File(int a_array[], FILE *report_pointer)
{
for(int i=0; i<5; i++)
{
printf("%i\n", a_array[i]);
fprintf(report_pointer, "%i\n", a_array[i]);
}
}
/*----------------------------------------------------------------------*/
//This function closes the file.
void end_function(FILE *file_pointer, FILE *report_pointer)
{
fclose(file_pointer);
fclose(report_pointer);
//closes both files we worked on.
}