• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Create and/or Write to a file

I feel like this should be easy, but google is totally failing me at the moment. I want to open a file, or create it if it doesn't exist, and write to it.

The following

throws an error on the second line when the file doesn't exist yet, which I assume is expected. But I'm really failing at finding out how to a) test if the file exists and b) create it when needed.

FYI, working in Delphi XE.

RBA's user avatar

5 Answers 5

You can use the FileExists function and then use Append if exist or Rewrite if not.

RRUZ's user avatar

Any solution that uses FileExists to choose how to open the file has a race condition. If the file's existence changes between the time you test it and the time you attempt to open the file, your program will fail. Delphi doesn't provide any way to solve that problem with its native file I/O routines.

If your Delphi version is new enough to offer it, you can use the TFile.Open with the fmOpenOrCreate open mode, which does exactly what you want; it returns a TFileStream .

Otherwise, you can use the Windows API function CreateFile to open your file instead. Set the dwCreationDisposition parameter to OPEN_ALWAYS , which tells it to create the file if it doesn't already exist.

Rob Kennedy's user avatar

You should be using TFileStream instead. Here's a sample that will create a file if it doesn't exist, or write to it if it does:

Ken White's user avatar

If you are just doing something simple, the IOUtils Unit is a lot easier. It has a lot of utilities for writing to files.

procedure WriteAllText(const Path: string; const Contents: string); overload; static; Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

awmross's user avatar

You can also use the load/save feature in a TStringList to solve your problem.

This might be a bad solution, because the whole file will be loaded into memory, modified in memory and then saved to back to disk. (As opposed to your solution where you just write directly to the file). It's obviously a bad solution for multiuser situations.

But this approach is OK for smaller files, and it is easy to work with and easy understand.

Jørn E. Angeltveit's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged delphi delphi-xe or ask your own question .

Hot Network Questions

assign file delphi

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

System.IOUtils.TDirectory.GetFiles

Description

Returns a list of files in a given directory.

Use GetFiles to obtain a list of files in a given directory. The return value of GetFiles is a dynamic array of strings in which each element stores the name of a file.

There are three forms of the GetFiles method:

All the forms also accept an optional TFilterPredicate parameter, used to filter the results.

The following table lists the parameters expected by this method.

Navigation menu

Personal tools.

RAD Studio 10.4 Sydney

RAD Studio 10.4 Libraries

In Other Languages

Previous versions.

Create a Database Using Delphi's File Of Typed Files

Understanding typed files.

Dimitri Otis/Getty Images

Simply put a file is a binary sequence of some type. In Delphi , there are three classes of file : typed, text, and untyped . Typed files are files that contain data of a particular type, such as Double, Integer or previously defined custom Record type. Text files contain readable ASCII characters. Untyped files are used when we want to impose the least possible structure on a file.

Typed Files

While text files consist of lines terminated with a CR/LF ( #13#10 ) combination, typed files consist of data taken from a particular type of data structure .

For example, the following declaration creates a record type called TMember and an array of TMember record variables.

Before we can write the information to the disk, we have to declare a variable of a file type. The following line of code declares an F file variable.

Note: To create a typed file in Delphi, we use the following syntax :

var SomeTypedFile : file of SomeType

The base type (SomeType) for a file can be a scalar type (like Double), an array type or record type. It should not be a long string, dynamic array, class, object or a pointer.

To start working with files from Delphi, we have to link a file on a disk to a file variable in our program. To create this link, we must use AssignFile procedure to associate a file on a disk with a file variable.

Once the association with an external file is established, the file variable F must be 'opened' to prepare it for reading and writing. We call Reset procedure to open an existing file or Rewrite to create a new file. When a program completes processing a file, the file must be closed using the CloseFile procedure. After a file is closed, its associated external file is updated. The file variable can then be associated with another external file.

In general, we should always use exception handling ; many errors may arise when working with files. For example: if we call CloseFile for a file that is already closed Delphi reports an I/O error. On the other hand, if we try to close a file but have not yet called AssignFile, the results are unpredictable.

Write to a File

Suppose we have filled an array of Delphi members with their names, e-mails, and number of posts and we want to store this information in a file on the disk. The following piece of code will do the work:

Read from a File

To retrieve all the information from the 'members.dat' file we would use the following code :

Note: Eof is the EndOfFile checking function. We use this function to make sure that we are not trying to read beyond the end of the file (beyond the last stored record).

Seeking and Positioning

Files are normally accessed sequentially. When a file is read using the standard procedure Read or written using the standard procedure Write, the current file position moves to the next numerically ordered file component (next record). Typed files can also be accessed randomly through the standard procedure Seek, which moves the current file position to a specified component. The FilePos and FileSize functions can be used to determine the current file position and the current file size.

Change and Update

You've just learned how to write and read the entire array of members, but what if all you want to do is to seek to the 10th member and change the e-mail? The next procedure does exactly that:

Completing the Task

That's it—now you have all you need to accomplish your task. You can write members' information to the disk, you can read it back, and you can even change some of the data (e-mail, for example) in the "middle" of the file.

What's important is that this file is not an ASCII file , this is how it looks in Notepad (only one record):

assign file delphi

By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts.

Home > Others

Delphi AssignFile Usage

1. text File New and read use

Put a button on the form and click Enter

Procedure Tform1.button1click (Sender:tobject); Var Bat:textfile; Begin AssignFile (Bat, ' c:\123.txt '); Create and open a file Rewrite (BAT); The Rewrite process can create a new file and open it, using the Reset Text files are read-only, and text files opened with rewrite and append can only be written to Writeln (Bat, ' 1111111111111111 '); Write Data CloseFile (BAT); Close File End

This creates a new 123.txt text file on the C drive and writes 1111111111111111 of the data.

2. Reading a text file

Procedure Tform1.button1click (Sender:tobject); Var Bat:textfile; s:string; Begin AssignFile (Bat, ' c:\123123.bat '); Reset (BAT); READLN (bat,s); Memo1. Lines.add (s); CloseFile (BAT); End

Procedure or

function Description Append Open the existing text file (to append text to the file). AssignFile Specifies the filename of the external file to a file variable. Blockread Reads one or more records from an untyped file. Blockwrite Writes one or more records to an untyped file. ChDir Changes the current directory. CloseFile Close the open file. Eof Returns the file end (end-of-file) state of the file. Eoln Returns the line end (end-of-line) state of a text file. Erase Delete the external file. Filepos Returns the current location of a type file or untyped file. FileSize Returns the current size of the file, not for a text file. Flush Refreshes the buffer of the output text file. Getdir Returns the current directory for the specified drive. IOResult Returns an integer value that represents the execution state of the last I/O function. Mkdir Create subdirectories. Read Reads one or more values from a file to one or more variables. Readln Performs a read operation in a text file and jumps to the beginning of the next line. Rename Rename the external file. Reset Open the file that exists. Rewrite Create and open a new file. RmDir Deletes an empty subdirectory. Seek Moves from the current position of a type file or untyped file to the specified component, not to a text file. Seekeof Returns the file end (end-of-file) state of a text file. Seekeoln Returns the line end (end-of-line) state of a text file. Settextbuf Specifies the input/output (I/O) buffer to a text file. Truncate Truncates a file at the current location of a type file or untyped file. Write Writes one or more values to a file. Writeln Performs a write operation in a text file and then writes a line end (End-of-line) tag. Function description Stralloc Assigning a character buffer of a given dimension to a heap Strbufsize Returns the size of the character buffer allocated with Stralloc or strnew StrCat Connect two strings StrComp Comparison of two strings Strcopy Copy a string Strdispose Releasing a character buffer allocated with Stralloc or strnew Strecopy Copy a string and return a tail pointer Strend Returns the end of the string pointer Strfmt Format one or more values into a string Stricomp Comparison of two strings (case insensitive) Strlcat Connect two strings (maximum length for a given result string) Strlcomp Comparison of two strings (given maximum length) Strlcopy Copies the string until the maximum length given StrLen Returns the length of a string Strlfmt Format one or more values into a string (the maximum length of a given string) Strlicomp Comparison of two strings (given maximum length and case insensitive) Strlower Convert a string to lowercase Strmove Move word converts sequential blocks from one string to another Strnew allocating strings in the heap Strpcopy Copy a Pascal string to an empty end string Strplcopy Copy a Pascal string to an empty end string (given maximum length) Strpos Returns the position pointer of the first occurrence of a given substring in a string Strrscan Returns the position pointer of the last occurrence of a given character in a string Strscan Returns the position pointer of the first occurrence of a given character in a string Strupper Convert a string to uppercase

This article is an English version of an article which is originally in the Chinese language on aliyun.com and is provided for information purposes only. This website makes no representation or warranty of any kind, either expressed or implied, as to the accuracy, completeness ownership or reliability of the article or any translations thereof. If you have any concerns or complaints relating to the article, please send an email, providing a detailed description of the concern or complaint, to [email protected] A staff member will contact you within 5 working days. Once verified, infringing content will be removed immediately.

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: [email protected] and provide relevant evidence. A staff member will contact you within 5 working days.

What's Trending

Top 10 Tags

Top 10 keywords, trending topic, a free trial that lets you build big.

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

Sales Support

1 on 1 presale consultation

After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.

Alibaba Cloud

A comprehensive suite of global cloud computing services to power your business

Payment Methods We Support

assign file delphi

Delphi in a Nutshell by Ray Lischner

Get full access to Delphi in a Nutshell and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

$Resource Compiler Directive

Description

The $Resource directive includes an external resource file in a project or package. When the project or package is linked, Delphi includes the resource file in the final .exe , .dll , or .bpl file. The resource file does not have to exist when the unit is compiled—only when the project is linked. A source file can load any number of resource files.

If the FileName is an asterisk ( * ), Delphi uses the source file’s base name, substituting the extension that appears in the directive. For example, form units must include the directive {$R *.DFM} , which loads the form’s description as a resource file. (To maintain compatibility with Delphi 1, binary .dfm files are 16-bit resource files. Delphi converts them to 32-bit resources when linking the project.)

The two-parameter form of the $Resource directive applies only to .dpr files. If the directive appears at the start of a project’s .dpr file and it lists two filenames, the first file is linked into the project, and the second appears in the project manager. When Delphi’s IDE builds the project, it also compiles the resource script ( .rc file) into a .res file so it can link the .res file with the project. Compiling the resource script is a feature unique to the IDE. The command-line compiler does not compile the resource script. (For more information on the command-line ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

assign file delphi

assign file delphi

PDFium – PDF Engine for your Delphi/C++ Builder FireMonkey Applications

assign file delphi

Table of Contents

PDFium Component Suite for FireMonkey has so many capabilities to handle PDF documents. It uses PDFium open-source PDF rendering engine and supports Windows, macOS, iOS, and Android.

PDFium itself is used by the Chromium project. So, you can understand that “ium” comes from Chromium! This is a fully open-source project and you can contribute to that here .

Installation

Since this is a component suite and supports different operating systems, it has its installation file. But, if you are in doubt, you can follow a short video on how to install the PDFium Component Suite for FireMonkey .

When you successfully install you will get two components on your Palette.

assign file delphi

TFPdf handles PDF documents. With that component, you can create and process PDF documents.

TFPdfView is the component that shows the PDF documents in your FireMonkey applications.

What you can do with the PDFium Suite?

Development

Let’s investigate how the PDFium Suite converting PDF documents to Jpg image files.

On Form Create this will get the pixels per inch by using the GetDisplayMetrics function.

The Convertor button starts the operation. It starts from page number 0, from the beginning. And with the RenderPage procedure, you can render the pages. And finally, you can save them to the TBitmap based data to files.

Extracting Images from PDF document

Taking file name and path and setting the initial point of the process is similar, but when you want to get images from PDF document. You can just iterate over the TFPdf using the BitmapCount and you can receive the images by its index.

Extracting Text

By calling Text function you can fetch the text from PDF documents and save the content to a text file:

Be sure to check out the demo action video that shows all the demo projects in action.

Head over and check out the full WINSOFT PDFium for FireMonkey Library

Like what you see? You can get PDFium for FireMonkey and over 100 other fantastic WinSoft components with our Enterprise Component Pack. For a limited time, when you purchase RAD Studio Enterprise or Architect Edition at special Upgrade Pricing, you will also get this package of third-party software worth over $13,000, including the full WinSoft Component Library, at NO EXTRA COST! Step up to RAD Studio 10.4.1 today!

What's Next

About author

assign file delphi

Is it possible to save in PDF/A format? And to sign with certificate?

assign file delphi

From what I can see it looks like PDFium cannot produce PDF/A format files. I do see that most of the component vendors have support for creating PDF/A though. You could try one of them.

This link talks about it: https://stackoverflow.com/questions/4804935/report-generators-that-can-produce-pdf-a-compliant-files So does this from TMS Software: https://doc.tmssoftware.com/flexcel/vcl/samples/delphi/printing-and-exporting/pdfa/index.html and Fast Report: https://www.fast-report.com/en/blog/show/export-pdf-a-delphi/ and WpCubed: http://www.wpcubed.com/pdf/products/wpdf/pdfa/

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Join Our Global Developer Community

Join our email list and receive the latest case studies, event updates, product news, and much more.

Object Pascal Handbook by Marco Cantú

Something Fresh

Why update subscription matters, and why march is a great time to renew your licenses, learn how to use template parameters in modern c++, how to check the c++ compiler version on windows, popular posts, announcing the availability of rad studio 11.3 alexandria.

assign file delphi

Some Suggestions to Help the Delphi Compiler

Jumpstart enterprise cloud development with aws, azure, and rad server.

assign file delphi

Delphi With Statements and Local Variables

All about apple arm on the desktop.

assign file delphi

Newest questions tagged delphi – Stack Overflow

Newest questions tagged interbase – Stack Overflow

Embarcadero

Embarcadero’s users understand the scalability and stability of C++ and Delphi programming, and depend on the decades of innovation those languages bring to development. Ninety of the Fortune 100 and an active community of more than three million users worldwide have relied on Embarcadero’s award-winning products over the past 30 years. Icons by Icons8.com .

© 2020 EMBARCADERO INC. ALL RIGHTS RESERVED

Useful Links

Privacy overview.

 alt=

IMAGES

  1. Copy in delphi code

    assign file delphi

  2. Curso de Delphi XE7 VARIABLES video 1

    assign file delphi

  3. 10 Fascinating Fact About Delphi

    assign file delphi

  4. File:Delphi-2.jpg

    assign file delphi

  5. class

    assign file delphi

  6. Delphi Sources

    assign file delphi

VIDEO

  1. [How to assign an external WAV file to a track on R20]

  2. how to use for in delphi 7

  3. Tutorial delphi : open form animated

  4. OpenStudio 0.6 Basic Workflow Guide (Building Activity, Thermal Zones, & Weather)

  5. 10-Delphi VCL Styles [Get styles from INI file ]

  6. 3-Delphi VCL Styles [Design form onCreate]

COMMENTS

  1. System.AssignFile

    Call AssignFile to initialize a file variable in Delphi code. F is a file variable of any file type. FileName is a string-type expression or an expression of type PChar if extended syntax is enabled. After calling AssignFile, F is associated with the external file until F is closed.

  2. delphi

    AssignFile (logFile, 'Test.txt'); Append (logFile); throws an error on the second line when the file doesn't exist yet, which I assume is expected. But I'm really failing at finding out how to a) test if the file exists and b) create it when needed. FYI, working in Delphi XE. delphi delphi-xe Share Improve this question Follow

  3. Delphi Basics : AssignFile command

    Delphi Basics : AssignFile command Description The AssignFile procedure assigns a value to FileHandle for a FileName in preparation for reading or writing to that file. Version 1 Takes a text file variable type as the handle. The file is treated as a textfile when opened.

  4. Delphi Basics : Assign command

    Delphi Basics : Assign command Description The Assign procedure is an obsolete version of AssignFile. The latter should always be used. Related commands AssignFile Assigns a file handle to a binary or text file Download this web site as a Windows program.

  5. System.IOUtils.TDirectory.GetFiles

    Description. Returns a list of files in a given directory. Use GetFiles to obtain a list of files in a given directory. The return value of GetFiles is a dynamic array of strings in which each element stores the name of a file.. There are three forms of the GetFiles method: . The first form accepts only the path of the directory for which files are enumerated.

  6. File I/O

    File I/O - Delphi Examples. There are 3 basic methods to perform File I/O. Use Pascal file variables. Use Windows API function wrappers. Use Windows API functions. The delphi help files suggest that you use the Pascal routines if you can. Use of the non-native Pascal file variable handlers such as FileOpen is discouraged.

  7. Create a Database Using Delphi's File Of Typed Files

    To start working with files from Delphi, we have to link a file on a disk to a file variable in our program. To create this link, we must use AssignFile procedure to associate a file on a disk with a file variable. AssignFile (F, 'Members.dat')

  8. Delphi AssignFile Usage

    1. text File New and read use Put a button on the form and click Enter Procedure Tform1.button1click (Sender:tobject); Var Bat:textfile; Begin AssignFile (Bat, ' c:\123.txt '); Create and open a file Rewrite (BAT); The Rewrite process can create a new file and open it, using the Reset

  9. $Resource Compiler Directive

    If the directive appears at the start of a project's .dpr file and it lists two filenames, the first file is linked into the project, and the second appears in the project manager. When Delphi's IDE builds the project, it also compiles the resource script ( .rc file) into a .res file so it can link the .res file with the project.

  10. PDFium

    Intro. PDFium Component Suite for FireMonkey has so many capabilities to handle PDF documents. It uses PDFium open-source PDF rendering engine and supports Windows, macOS, iOS, and Android. PDFium itself is used by the Chromium project. So, you can understand that "ium" comes from Chromium!