.
Совсем недавно в непомню какой коференции я видел запись какого-то человека, который просил, чтобы хоть кто-нибудь объяснил ему элементарную работу с файлами... Казалось бы такое простое... Но это простое для тех, кто уже хоть немного продвинулся в программировании, а кто это только начал? Это же, действительно, непроходимый лес! И я сильно сомневаюсь, чтобы кто-нибудь из других наших Web-мастеров когда-нибудь уделит этому хоть какое-то внимание. Поэтому этим займусь я и попробую в этой статье показать только основы.
1. Открытие файла для чтения информации из него.
Итак, чтобы безпроблемно работать с текстовыми файлами сначала их нужно открыть. Делается это с помощью оператора Open, например:
Open "c:text.txt" For Input As #1
Обратите внимание на режим открытия файла - Input (для чтения). Здесь файл text.txt открывается для считывания под номером 1. Внимание!!! Номер файла - обязательный параметр, и вводить его нужно всегда! Если ваша программа будет иметь дело не с одним десятком открытых файлов, то уследить за их нумерацией будет сложновато. Используйте для этого функцию FreeFile. Она возвращает ещё не занятый номер (от 1 до 511) для файла:
Dim FileNum As Integer
FileNum = FreeFile
Open "c:text.txt" For Input As FileNum
Так, файл открыли! Теперь из него нужно что-нибудь считать. Оператор Line Input считывает из открытого файла по одной строке при каждом вызове. Поэтому для считывания из файла нужно построить цикл, который бы вызывал этот оператор до тех пор, пока не дошёл бы до конца файла:
цикл выполняется, пока конец файла не достигнут
Do Until EOF(FileNum)
при каждом вызове оператора Line Input он записывает в
переменную новою строку
Line Input #FileNum, переменная
Loop
Закрыть открытый файл можно оператором Close #FileNum. А теперь вот как это должно выглядеть в практике:
Dim FileNum As Integer
Dim txt As String
Dim alltxt As String
FileNum = FreeFile
открываем файл в режиме чтения
Open "c:text.txt" For Input As FileNum
запускаем вышеупомянутый цикл
Do Until EOF(FileNum)
считываем строку из файла с номером FileNum и кладём её в
переменную txt
Line Input #FileNum, txt
теперь к переменной alltxt добавляем содержимое переменной txt -
строки и vb-константу vbCrLf (Chr(13)+Chr(10)), т.к. каждая строка
должна быть с новой строки :-)
alltxt = alltxt + txt + vbCrLf
Loop
закрываем файл с номером FileNum
Close #FileNum
выводим содержимое переменной alltext
MsgBox alltxt
2. Открытие файла для записи информации в него.
Записать информацию в файл ещё проще!!! Эта операция отличается от предыдущей только тем, что открыть файл надо в режиме записи:
Open "c:text.txt" For Output As FileNum
и вместо цикла нужно вставить оператор Print #, который записывает в файл содержимое переменной:
Print #FileNum, "Азбука Visual Basic"
или
Print #FileNum, alltext
Пример:
Dim FileNum As Integer
Dim txt As String
FileNum = FreeFile
txt = "members.tripod.de/cmvb"
открываем файл в режиме записи
Open "c:text.txt" For Output As FileNum
Print #FileNum, txt
закрываем файл с номером FileNum
Close #FileNum
Проверьте содержимое файла.
И ещё хочу предложить второй способ записи информации в файл - с помощью API-функции WritePrivateProfileStringByKeyName. Считывать же информацию нужно с помощью API-функции GetPrivateProfileString. Теперь расскажу - как всё это работает?
1.Создайте стандартный проект.
2.Введите модуль.
3.Удалите форму и кликните два раза по модулю.
4.В раздел General Declarations следующее объявление двух, вышеназванных функций:
Declare Function GetPrivateProfileString& Lib _
"kernel32" Alias "GetPrivateProfileStringA" (ByVal _
lpszSection$, ByVal lpszKey$, ByVal lpszDefault$, _
ByVal lpszReturnBuffer$, ByVal cchReturnBuffer&, _
ByVal lpszFile$)
lpszSection -имя секции
lpszKey - имя ключа
lpszDefault - значение, возвращаемое по умолчанию, при строке ""
lpszReturnBuffer - место для строки
cchReturnBuffer - размер (длина) места для строки
lpszFile - имя файла
Declare Function WritePrivateProfileStringByKeyName% Lib _
"kernel32" Alias "WritePrivateProfileStringA" (ByVal _
lpApplicationName As String, ByVal lpKeyName As String, _
ByVal lpString As String, ByVal lplFileName As String)
lpApplicationName - имя секции
lpKeyName - имя ключа
lpString - строка
lplFileName - имя файла
5.Создайте подпрограмму Main - просто введите Sub Main.
6.В подпрограмму Main введите:
Sub Main()
создаём файл test.ini, в нём заголовок "Main", ключ "URL" _
и строку "members.tripod.de/cmvb"
Call WritePrivateProfileStringByKeyName("Main", "URL", _
"members.tripod.de/cmvb", "c:test.ini")
создаём файл test.ini, в нём заголовок "Main", ключ "eMail" _
и строку "v1500mk@t-online.de"
Call WritePrivateProfileStringByKeyName("Main", "eMail", _
"v1500mk@t-online.de", "c:test.ini")
End Sub
При запуске проекта на диске С: тут же будет создан файл Test.ini со следующим содержимым:
[Main]
URL=members.tripod.de/cmvb
eMail=v1500mk@t-online.de
8:-O!!! Не правда ли, просто? А считать это чуть-чуть сложнее. Итак, файл создан, теперь поробуем считать информацию оттуда. Удалите всё, что находится между строками "Sub Main()" и "End Sub". Впишите следующее:
Sub Main()
создаём переменную, в которую будет передоваться строка
Dim MyString As String
"набиваем" её пробелами
MyString = Space(100)
открывается файл файл test.ini, и в переменную MyString _
записывается строка из заголовка "Main", ключа "URL"
Call GetPrivateProfileString("Main", "URL", "", MyString, _
Len(MyString), "C:test.ini")
выводится на экран содержимое переменной MyString
MsgBox MyString
открывается файл файл test.ini, и в переменную MyString _
записывается строка из заголовка "Main", ключа "eMail"
Call GetPrivateProfileString("Main", "eMail", "", MyString, _
Len(MyString), "C:test.ini")
выводится на экран содержимое переменной MyString
MsgBox MyString
End Sub
Другие работы по теме:
Визуальное программирование
Визуализация - это процесс графического отображения сложных процессов (в данном случае построения) на экране компьютера в виде графических примитивов (графических фигур).
Greating 3D-Graphics on visual basic
Program automatic system on visual basic for graiting 3D-Graphics. Text of source code for program functions. Setting the angle and draw the rotation. There are functions for choose the color, finds the normal of each plane, draw lines and other.
Завадостійке кодування на основі циклічних кодів
Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CRC32", "CRC32CRC32.csproj", "{EE28F805-6DA0-4E7B-89A5-A3B245E1441D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Debug|Any CPU.Build.0 = Debug|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Release|Any CPU.ActiveCfg = Release|Any CPU {EE28F805-6DA0-4E7B-89A5-A3B245E1441D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE
Мови та системи програмування
ІНФОРМАТИКА Тема: Мови та системи програмування Однією з найпоширеніших мов з програмування серед сучасних мов високого рівня, що використовуються в ПК, є мова Visual BASIC.
Microsoft Visual Basic 5 0
Microsoft Visual Basic 5.0 Microsoft Visual Basic 5.0 - это мощная система программирования, позволяющая быстро и эффективно создавать приложения для Microsoft Windows’95 и Microsoft Windows’NT
Color Theory Essay Research Paper Color TheoryColor
Color Theory Essay, Research Paper Color Theory Color theory encompasses a multitude of definitions, concepts and design applications. All the information would fill several encyclopedias. As an introduction, here are a few basic concepts.
Light Matter Essay Research Paper Inner LightIn
Light Matter Essay, Research Paper Inner Light In order to understand what light is one has to understand how vision works. The process of visual perception is incredibly complex, involving many functions of the brain. In Arthur Zajonc’s book “Catching the Light,” he writes, “?vision requires far more than a functioning physical organ.
Baby Eye Testing Essay Research Paper U
Baby Eye Testing Essay, Research Paper U OF T PROFESSORS DEVISE BETTER WAY TO TEST SIGHT IN BABIES In a darkened room at Toronto’s Hospital for Sick Children, a baby, its head dotted with electrodes, sits in its mother’s lap and watches flashing black and white checkerboards and stripes on a television screen.
Senseless A False Sense Of Perception Essay
, Research Paper Senseless: A False Sense of Perception I feel as though I have no choice but to be a skeptic about our ability to know the world on the sense experience given the information that is being
Convergence Of The Twain Essay Research Paper
“The Convergence of the Twain” Personification is “endowing inanimate objects or abstract ideas with life or human characteristics” (Kirszner 2058). In the poem “The Convergence of the Twain” the author?s use of personification allows the reader to make a more fluid transition from the past to the present.
The NonDesigner
’s Design Book Essay, Research Paper The Non-Designer s Design Book By Robin Williams I chose this book because I am very interested in the design of a page, whether it be an advertisement, invitation, or feature story. I learned some important principles to follow. This book was easy to read and understand.
Programming Languaguages Essay Research Paper Programming LanguagesA
Programming Languaguages Essay, Research Paper Programming Languages A programming language is a set of English-like instructions that includes a set of rules for putting the instructions together to create commands. A translator changes the English-like commands into numeric code that the computer can understand.
Costa Sakellariou Essay Research Paper Costa Sakellariou
Costa Sakellariou Essay, Research Paper Costa Sakellariou Visual art can definitely be seen as a language. With every artist there is always some sort of meaning that they are trying to convey to the viewers of their work. The means of how they deliver that message is the language in which their work uses. In Costa Sakellariou?s work I especially felt there was some sort of language being spoken.
Learning Styles Essay Research Paper Every person
Learning Styles Essay, Research Paper Every person learns differently. From kindergartner to postgraduate levels, only students can do the earning, and they do it in their own particular, individual learning styles. Some children pick something up the first time they hear it. Others may not grasp a concept until they?ve had the chance to see it in print, or to write it themselves.
Learning Styles Essay Research Paper LEARNING STYLESPeople
Learning Styles Essay, Research Paper LEARNING STYLES People not only learn at different rates, but also in different ways. Some people want everything written down, others prefer to listen. Some prefer small group settings rather than large group discussions; others like to listen to a lecture and translate it into pictorial doodles in a notebook.
Learning Styles Compare
& Contrast Essay, Research Paper Learning Styles The purpose of this paper is to identify and compare the meaning as well as the differences of two learning styles as they relate to both the academic and professional realm. I have chosen these two styles because I believe the majority of people are either visual or auditory learners.
The Brain
’s Cerebral Cortex Essay, Research Paper The brain is three pounds of tissue that are part of the nervous system. It is one of the two basic parts and contains a bout 100 billion nerve cells.
Visual Art Essay Research Paper VISUAL ARTS
Visual Art Essay, Research Paper VISUAL ARTS “The physical impossibility of death in the mind of someone living” By Damien Hirst (photo courtesy of the saatchi collection)
Dragon Ball Z Web Pages Essay Research
Paper When I think of cartoons, I think of Dragon Ball Z. dragon Ball Z is an Anime series from Japan, currently airing on cartoon Network. When I received this assignment I
Memory Essay Research Paper Memory is the
Memory Essay, Research Paper Memory is the process of storing and retrieving information in the brain. Memory is viewed as a three-step process, which include sensory memory, short-term memory, and long-term memory. Along with memory there is also forgetting. There are two types of forgetting, availability and accessibility.
Dover Beach Essay Research Paper Dover Beachby
Dover Beach Essay, Research Paper ?Dover Beach? by: Matthew Arnold In the poem ?Dover Beach? by: Matthew Arnold there is a lot of irony, appeal to the auditory and visual sense, and illusions. The tone in this poem is very sad and dismal, but he shows us how to keep faith and hope in spite of that and how important being honest, true, and faithful to one another, really is.
Metric System Essay Research Paper Metric SystemThe
Metric System Essay, Research Paper Metric System The Metric System, also known as the System Internationale (SI) was developed in France in 1799. The Metric System was created because the French and English were not in agreement politically, therefore the French did not want anything to do with the English including their system of measurements.
Art 5 Essay Research Paper ArtArt comes
Art 5 Essay, Research Paper Art comes in many different forms. It isn t just visual work done on canvas using a certain medium, like pencils, watercolors, or oils. Art is just a way in which an individual expresses his or her inner most self, so that others can understand that individuals personality or feelings to their fullest.
Design Structure Essay Research Paper Basic ideas
Design Structure Essay, Research Paper Basic ideas and Concepts of Software DesignAn Interface to the End-UserThe Project Management System was designed with the goal that the end-user can handle the system on his own.The interactive user interface is based on the Windows interface.The interface programs use standard software of the market like Visual Basic, Microsoft Access and Crystal Reports.DocumentationThe software should be documented.
What Are Visual Defects And How Common
Are They ? Essay, Research Paper What Are Visual Defects and How Common Are They ? Nate Schackow 2nd Period December 17, 1996 The human eye does alot more than allowing you to see. It is very
Is Cobol Dead Essay Research Paper Is
Is Cobol Dead Essay, Research Paper Is COBOL dead? To be completely honest, I originally had no idea. I knew that I took it as programming class last semester, but I didn’t know how it applied to the business world. Nor, had it ever crossed my mind in the 3+ months that I used it. The fact that you asked the question made me wonder myself, so I had to do some reading.
Basic TrainingMen And Women Together Essay Research
Paper Should Men and Women Take Basic Training Together The Untied States Armed Forces consist of the Army, Navy, Air Force, and Marines; it has been in existence for many years. The first step of military life once someone joins is basic training. Just as the name implies, it is here where a recruit learns the first skills of being a warrior and how to fight battles.
The Job Of A Graphic Designer Essay
, Research Paper Graphic designers create the visual presentation and design of goods, from gravestone markers to detergent boxes, from album covers to dog food cans (The Princeton Review Guide to Your Career.) Graphic artists, or graphic designers, are the bases of the graphic world. It is their designs that are sent to layout artists and then to the printers and then onto the outside world on cd covers, cereal boxes, billboards, posters, and basically anything that has to do with a visual representation.