Home Computer Tutorials Computer Knowledge How to assign file data to structure variables in C language

How to assign file data to structure variables in C language

Jan 12, 2024 pm 03:27 PM

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:

How to assign file data to structure variables in C language

Run screenshot:

How to assign file data to structure variables in C language

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Solve Windows Error Code "INVALID_DATA_ACCESS_TRAP" (0x00000004) How to Solve Windows Error Code "INVALID_DATA_ACCESS_TRAP" (0x00000004) Mar 11, 2025 am 11:26 AM

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

ENE SYS Maintenance: Tips and Tricks to Keep Your System Running Smoothly ENE SYS Maintenance: Tips and Tricks to Keep Your System Running Smoothly Mar 07, 2025 pm 03:09 PM

This article provides practical tips for maintaining ENE SYS systems. It addresses common issues like overheating and data corruption, offering preventative measures such as regular cleaning, backups, and software updates. A tailored maintenance s

5 Common Mistakes to Avoid During ENE SYS Implementation 5 Common Mistakes to Avoid During ENE SYS Implementation Mar 07, 2025 pm 03:11 PM

This article identifies five common pitfalls in ENE SYS implementation: insufficient planning, inadequate user training, improper data migration, neglecting security, and insufficient testing. These errors can lead to project delays, system failures

How do I edit the Registry? (Warning: Use with caution!) How do I edit the Registry? (Warning: Use with caution!) Mar 21, 2025 pm 07:46 PM

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.

Discover How to Fix Drive Health Warning in Windows Settings Discover How to Fix Drive Health Warning in Windows Settings Mar 19, 2025 am 11:10 AM

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.

How do I manage services in Windows? How do I manage services in Windows? Mar 21, 2025 pm 07:52 PM

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

why won't driver asio.sys load why won't driver asio.sys load Mar 10, 2025 pm 07:58 PM

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

which application uses ene.sys which application uses ene.sys Mar 12, 2025 pm 01:25 PM

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

See all articles