我正在尝试从目录中获取文件并将其保存在内存中,目标是将信息从文件结构逐个结构复制到 tmp 文件中,进行一些编辑,然后将新信息保存在新数据中文件。我现在要做的就是获取文件然后打印它。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
typedef struct hw5_struct {
char f_name[12];
char l_name[12];
int age;
float height;
}HW5_struct;
void printThisFile( FILE *data );
int main( int argc, char *argv[] ) {
const char *fileLocation = argv[1];
FILE *originalData = fopen( fileLocation, "r" );
if( access( fileLocation, F_OK ) != -1 )
printf("The file at %s exists\n", argv[1]);
printThisFile( originalData );
//int sizeOfOriginalData = sizeOf( &originalData );
}
void printThisFile( FILE *data ) {
printf( "printThisFile called\n" );
int c;
if ( data ) {
printf( "printing file contents now:\n" );
while( ( c = getc( data ) ) != EOF )
printf("%c", c);
fclose( data );
}
}
它打印以下内容:
FredHutcheson À@LarryStarchÍ̼@LucyLu-FredFlintstone 33£@BarnyRubbleÍÌl@AmandaHelix33³@RobertHenderson7ffÆ@BobbyNLMcÍ̼@BettyDurnanJPBFloodProfÀ@
我真的不知道它到底应该是什么样子,但绝对不是那样。
最佳答案
如果写入该文件的内容正在写入 hw5_struct
的二进制版本,这将是有意义的
如果是这种情况,您需要通过执行相应的二进制读取来加载文件
FILE *originalData = fopen( fileLocation, "rb");
HW5_struct tempStruct;
fread(&tempStruct, sizeof(hw5_struct),1, data);
然后您可以通过打印位将其拆开。
printf("%s %s %d %f\n", tempStruct.f_name, tempStruct.l_name,tempStruct.age, tempStruct.height);
您当前的读取代码仅适用于文本文件。
关于c - 在c中打印出数据文件是完全错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46658904/