


How to assign file data to structure variables in C language
/*The sex[2] given does not seem to fit 4 letters. . . . . . But I understand the meaning of the question.
**In order to simplify programming, I changed all the data in the structure into character arrays. If numbers are needed, just add another step of conversion**. It is relatively simple and I won’t write it. In addition, it is used in the program A structure array. If you are not sure how many lines there are in the file, in order to save memory, you can use dynamic allocation. It was written in a hurry, and there is no encapsulated function, but it is indeed usable, so just make do with it~~~
*/
#include <...>
struct employ
{
char id[10];
char name[10];
char sex[5];
char age[5];
char edu[10];
char wage[5];
char address[20];
char number[20];
};
int _tmain(int argc, _TCHAR* argv[])
{
char buf[100];
FILE* pf=NULL;
struct employ Ep[10]={};
int flag=0;
pf=fopen("employ.dat","r");
if(!pf)
{
printf("File opening failed!\n");
system("pause");
return -1;
}
while(fgets(buf,99,pf))
{
char* pchar=buf;
for(int i=0;i
{
Ep[flag].id[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].name[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].sex[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].age[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].edu[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].wage[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].address[i]=*pchar;
if(*pchar ==',')
break;
}
for(int i=0;i
{
Ep[flag].number[i]=*pchar;
if(!*pchar )
break;
}
//printf("%s",buf);
flag;
}
fclose(pf);
system("pause");
return 0;
}
How to use data variables in txt files in c language
Use fopen and fscanf functions to read content from txt files and perform simple operations.
1.Fopen function prototype: FILE * fopen(const char * path, const char * mode);
The first parameter of the fopen function is the file path, and the second parameter is the opening method. There are the following methods:
r Open the file in read-only mode. The file must exist.
r Open the file in read-write mode. The file must exist.
rb opens a binary file for reading and writing, allowing data to be read.
rw Read and Write Opens a text file, allowing reading and writing.
w Open a write-only file. If the file exists, the file length will be cleared to 0, that is, the file content will disappear. If the file does not exist, create the file.
w Open a readable and writable file. If the file exists, the file length will be cleared to zero, that is, the file content will disappear. If the file does not exist, create the file.
a Open a write-only file in append mode. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained. (EOF character reserved)
a Open a read-write file in append mode. If the file does not exist, the file will be created. If the file exists, the written data will be added to the end of the file, that is, the original content of the file will be retained. (The original EOF character is not retained)
wb Open or create a new binary file for writing only; only data writing is allowed.
wb read and write Open or create a binary file, allowing reading and writing.
wt Open or create a text file for reading and writing; reading and writing are allowed.
at opens a text file for reading and writing, allowing reading or appending data to the end of the text.
ab opens a binary file for reading and writing, allowing reading or appending data to the end of the file.
The above-mentioned form strings can be added with a b character, such as rb, w b or ab, etc. The b character is added to tell the function library that the file opened is a binary file, not a plain text file.
Return value: After the file is successfully opened, the file pointer pointing to the stream will be returned. If the file opening fails, NULL is returned and the error code is stored in errno.
2. Routine:
1
2
3
4
5
6
7
8
9
10
11
12
#include
#define F_PATH "d:\\myfile\\file.dat"
charc;
intmain(){
FILE*fp=NULL; //Need to pay attention
fp=fopen(F_PATH,"r");
if(NULL==fp) return-1; //To return an error code
while(fscanf(fp,"%c",&c)!=EOF) printf("%c",c); //Read from the text and print it out on the console
fclose(fp);
fp=NULL; //Needs to point to null, otherwise it will point to the original opened file address
return0;
}
How does C voice read a certain line in a txt file and assign it to a variable
The simplest method is to read line by line, but only get the line of data you want. Below is a simple example I wrote. I drew prizes three times and there were no duplicates.
#include
#include
#include
#define PEOPLE_NUM 10 //There are 10 names in my file
void get_prize(FILE* fp, char prize_name[])
{
int num;
int i;
fseek(fp, 0, SEEK_SET);
printf("start...\n");
num = rand() % PEOPLE_NUM 1;
for(i = 0; i
{
fgets(prize_name, 32, fp);
}
printf("%s get the prize!!!\n", prize_name);
}
int main()
{
FILE* fp = fopen("name.txt", "r");
int prize_num;
int i;
char prize_name[32] = {0};
srand(time(0));
for(i = 0; i
{
printf("\n");
get_prize(fp, prize_name);
}
fclose(fp);
return 0;
}The file looks like this:
Run screenshot:
When writing this kind of program, the files where you save names must be arranged neatly so that the program can process them easily. good luck.
The above is the detailed content of How to assign file data to structure variables in C language. For more information, please follow other related articles on the PHP Chinese website!

This article addresses the Windows "INVALID_DATA_ACCESS_TRAP" (0x00000004) error, a critical BSOD. It explores common causes like faulty drivers, hardware malfunctions (RAM, hard drive), software conflicts, overclocking, and malware. Trou

Article discusses editing Windows Registry, precautions, backup methods, and potential issues from incorrect edits. Main issue: risks of system instability and data loss from improper changes.

Article discusses managing Windows services for system health, including starting, stopping, restarting services, and best practices for stability.

What does the drive health warning in Windows Settings mean and what should you do when you receive the disk warning? Read this php.cn tutorial to get step-by-step instructions to cope with this situation.

This article identifies ene.sys as a Realtek High Definition Audio driver component. It details its function in managing audio hardware, emphasizing its crucial role in audio functionality. The article also guides users on verifying its legitimacy

This article addresses the failure of the Windows asio.sys audio driver. Common causes include corrupted system files, hardware/driver incompatibility, software conflicts, registry issues, and malware. Troubleshooting involves SFC scans, driver upda

The article explains how to use the Group Policy Editor (gpedit.msc) in Windows for managing system settings, highlighting common configurations and troubleshooting methods. It notes that gpedit.msc is unavailable in Windows Home editions, suggesting

Article discusses changing default apps for file types on Windows, including reverting and bulk changes. Main issue: no built-in bulk change option.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.