1、文档格式
读取每行数据,并解析为号码和地址,分别打印。
void readline(FILE *file);
int main()
{
//设置区域,支持宽字符
setlocale(LC_CTYPE, "");
FILE *file = fopen("location.txt", "rb");//UTF-16LE,以二进制格式只读打开
if (file == NULL) {
wprintf(L"Error opening file.\n");
return 1;
}
fseek(file,2L,SEEK_CUR);//跳过两字节,BOM
readline(file);//调用
fclose(file);// Close the file
return 0;
}
void readline(FILE *file)
{
wchar_t buffer[256];//存储每行数据
int number;//存储号码
wchar_t address[256];//存储地址
//遍历每行,并输出
while (fgetws(buffer, 256, file) != NULL) {
// 解析行数据,tab间隔符
if (swscanf(buffer, L"%d\t%ls",&number, address) == 2) {
//打印每行数据
wprintf(L"No: %d, Address: %ls\n", number, address);
} else {
wprintf(L"Error parsing line: %ls\n", buffer);
}
}
}
3、构建数据链表
typedef struct Node
{
int number;//号码
wchar_t address[256];//地址
struct Node * pNext;
}NODE, * PNODE;
调整上述函数,构建数据链表,并打印。
typedef struct Node
{
int number;//号码
wchar_t address[256];//地址
struct Node * pNext;
}NODE, * PNODE;
void readline(FILE *file,PNODE *pHead);
int iniList(PNODE *pHead,FILE *file);
void printList(PNODE pHead);
int main()
{
//设置区域,支持宽字符
setlocale(LC_CTYPE, "");
FILE *file = fopen("location.txt", "rb");//UTF-16LE,以二进制格式只读打开
if (file == NULL) {
wprintf(L"Error opening file.\n");
return 1;
}
fseek(file,2L,SEEK_CUR);//跳过两字节,BOM
PNODE pHead;
readline(file,&pHead);//调用
fclose(file);// Close the file
wprintf(L"===============================================\n");
printList(pHead);
return 0;
}
void readline(FILE *file, PNODE *pHead)
{
wchar_t buffer[256];//存储每行数据
//int number;//存储号码
//wchar_t address[256];//存储地址
*pHead =(PNODE)malloc(sizeof(NODE));
if (!pHead)
{
wprintf(L"Error malloc\n");
return;
}
(*pHead)->number=0;
memset((*pHead)->address,0,256);
(*pHead)->pNext=NULL;
PNODE pnail = *pHead;
PNODE pnew;
//遍历每行,并输出
while (fgetws(buffer, 256, file) != NULL) {
pnew=(PNODE)malloc(sizeof(NODE));
if (!pnew)
{
wprintf(L"Error malloc\n");
return;
}
// 解析行数据,tab间隔符
if (swscanf(buffer, L"%d\t%ls",&(pnew->number),pnew->address) == 2) {
//wprintf(L"No: %d, Address: %ls\n", pnew->number, pnew->address);
pnail->pNext=pnew;
pnail=pnew;
pnail->pNext=NULL;
pnew=NULL;
} else {
wprintf(L"Error parsing line: %ls\n", buffer);
}
}
pnew = *pHead;
free(pnew);
*pHead=(*pHead)->pNext;
}
void printList(PNODE pHead)
{
PNODE p;
while(pHead!=NULL)
{
p=pHead;
//打印数据
wprintf(L"No: %d, Address: %ls\n", p->number, p->address);
pHead=pHead->pNext;
free(p);
}
}