Error cannot open file for writing

When I compile my source code to run, sometimes it leads to question like that. I don't know the reason of this problem, and I want to ask how I can solve this problem? It is the first time I ask

When I compile my source code to run, sometimes it leads to question like that. I don’t know the reason of this problem, and I want to ask how I can solve this problem?

It is the first time I ask question there. It seems that I fail to upload the picture.

enter image description here

I can’t close the background process here.

asked Mar 4, 2017 at 2:22

Werther's user avatar

WertherWerther

431 silver badge7 bronze badges

2

You left your program running when you tried to recompile it, so it couldn’t replace the old program with the new one.

answered Mar 4, 2017 at 2:28

Joseph Sible-Reinstate Monica's user avatar

1

Restart your computer, your program did not end successfully!

answered Mar 4, 2017 at 2:41

Kevin Duarte's user avatar

Kevin DuarteKevin Duarte

4261 gold badge4 silver badges13 bronze badges

You are here: Home / Windows / 10 Fixes For Error Opening File For Writing On Windows 11/10

This article has been updated to stay relevant for Windows 11 and 10 users. 

error-opening-file-for-writing

Errors that appear during installation are surely the worst kind. The error opening file for writing has been reported by many users for a long time, and it appears while trying to install certain applications.

This error mainly appears for writing MSI Afterburner, Steam, vcredist_x86.exe, VLC, and some other commonly used applications.

Here we have discussed how to solve this error, so keep reading!

Why You Cannot Open File For Writing?

Contents

  • 1 Why You Cannot Open File For Writing?
  • 2 How To Fix Error Opening File For Writing
    • 2.1 Solution 1: Close All Background Installation Processes
    • 2.2 Solution 2: Delete Junk files
    • 2.3 Solution 3: Run The Compatibility Troubleshooter
    • 2.4 Solution 4: Run The Installer With Administrative Rights
    • 2.5 Solution 5: Change Security Permissions
    • 2.6 Solution 6: Change Advanced Security Permissions
    • 2.7 Solution 7: Create New User As Administrator
    • 2.8 Solution 8: Disable Your Antivirus
    • 2.9 Solution 9: Disable The User Account Control Feature
    • 2.10 Solution 10: Delete The Installer And Download It Again
  • 3 Wrapping Up

As per reports, this error is most common when setup files lack the required permissions as the setup file can’t open the file to write.

But, there can be other causes for this error, such as:

  • If the installation file is not compatible with your system, then it can cause such an error.
  • The antivirus is known to stop files from writing that it considers a threat to the computer, including installation files. Thus, the antivirus can be responsible for the error while opening the file.
  • The installation file itself can be corrupted causing this error.
  • If the installation process of the file is already running in the background and you try to start the installation again, then this error can get triggered.
  • Problems in registry or excess of junk files in the computer can also cause this error.

This error can be fixed with the following solutions. So, perform all of them and see which one solves it for you.

Solution 1: Close All Background Installation Processes

If one installation is already in process in the background and you are trying to start another installation, then this error can get triggered.

To ensure there are no installation processes in the background, follow the steps given below:

  1. Press Ctrl + Shift + Esc keys on your keyboard to open the Task Manager.
  2. Select the Processes tab, and check if any installation process is running.
    If yes, then right-click on it and click on the End task option.

end-task-steam

Try installing the file again. This solution should fix the problem if it was caused by another installation in the background.

Solution 2: Delete Junk files

If your computer has excess junk files, then it can cause this type of installation errors.

Fortunately, there are some in-built junk file cleaners in your Windows like the Storage sense and the Disk cleanup tool, which can be used to delete the junk files present in your computer.

After the junk files are removed, try to install the application again and check if the error persists.

Solution 3: Run The Compatibility Troubleshooter

If the installer file is incompatible with your Windows, then the installer can’t open the file to write and thus trigger this error.

Fortunately, there is an in-built compatibility troubleshooter in Windows that you can use to check the file’s compatibility.

To run the compatibility troubleshooter, follow the steps given below:

  1. Locate the installer file of the application that is causing this error for you and right-click on it.
  2. Click on the Properties option from the pop-up menu.

spotify-setup-properties

  1. Select the Compatibility tab and then click on the Run compatibility troubleshooter option.
  2. Select the Try recommended settings option and follow the instructions given by the wizard to run the compatibility troubleshooter.

run-compatibility-troubleshooter-for-spotify-setup

Try to install the file again and check if the installer is facing the same error. 

Solution 4: Run The Installer With Administrative Rights

This error mostly happens if the installer doesn’t have the required permissions to install the file. Running the installer as an administrator can fix the problem.

Here is how you can do it:

  1. First, locate the installer in your computer and right-click on it.
  2. Select the Run as administrator option.
  3. The application will now install while having administrator rights.

run-spotify-setup-as-administrator

If the error doesn’t arise again, then you will have to open this program each time in administrator mode to work around this problem or you can give this application permanent administrative rights.

To set the application to run as administrator whenever you open it, follow the steps given below:

  1. Locate the application on your computer and right-click on it.
  2. Click on the Properties options from the pop-up menu.

spotify-setup-properties

  1. Select the Compatibility tab and then select the Run this program as an administrator box.
  2. Finally, click on Apply and then OK to save the changes.

run-spotify-setup-always-as-administrator

Solution 5: Change Security Permissions

If running the installer as an administrator didn’t work, the check if you are signed in as a regular user account.

Regular users are not allowed to install applications if denied by the administrator. So, they can face this error when they try to install the application.

You can try changing the security permissions to allow the installer to function. To change the security permissions, follow the steps given below:

  1. Right-click on the application and select Properties.
  2. Next, select the Security tab and then click on the Edit option.

edit-permission-settings-from-spotify-properties

  1. Click on your account username in the Group or user names section.
  2. In the Permissions for Users section, locate the Write option and then check the box in the Allow section.

allow-write-permissions-to-user-account

  1. Finally, click on Apply and OK to save the changes.

By changing the security permissions, you should now be able to install the program without triggering the error during the installation.

Solution 6: Change Advanced Security Permissions

If changing the security permissions didn’t fix this error, then try changing the Advanced security permissions.

To change the Advanced security permissions, follow the steps given below:

  1. Follow Solution 5 and open the Security tab.
  2. Next, click on the Advanced option.

advanced-security-settings-from-spotify-properties

  1. Click on the Add option and click on the Select a principal option.

add-new-owner-for-permission-spotify-properties

  1. Type Everyone in the Enter the object name to select (examples) section and then click on the Check Names option. Click OK to save the changes.

create-new-principal-for-permission

  1. In the Basic permissions section, check the Full control box and click on OK to save the changes.

give-full-control-to-spotify-setup

  1. Now, from the Permission entries list, locate the Everyone element and select it.

Now, you should be able to install the application without triggering the error opening file for writing during the installation.

Solution 7: Create New User As Administrator

If you don’t want to change the security permissions, then try creating a new user account as an administrator and then install this application there.

To create a new user account as an administrator, follow the steps given below:

  1. Right-click on the Windows start button and then click on the Settings option from the pop-up menu.

open-settings-from-startmenu-context-menu

  1. Locate the Accounts option and open it.
  2. Now, select the Family & other users option (only Family for Windows 11).

family-settings-windows-11

  1. Then scroll down and click on the Add someone else to this PC (or only Add Someone for Window 11) option.

add-someone-in-family-windows-account-settings

  1. Click on the I don’t have this person’s sign-in information option.
  2. Next, click on the Add a user without a Microsoft account option. You will have to use another Microsoft account in Windows 11.

add-a-user-without-microsoft-account

  1. Now, enter the name and the password of the user account and then click on Next.
    This should create your new user account and you will be able to see it in the Other users section.
  2. Select the user account you just created and click on the Change account type option.
  3. Now, click on the Account type menu and select the Administrator option from the drop-down list.
    Click Ok to save the changes.
  4. Now, sign out of your current account and log in to your new user account.

Once you have switched to the new user, try installing the program and check if the setup still cannot open file for writing.

Solution 8: Disable Your Antivirus

Antiviruses are known instigators when it comes to stopping other files from opening or stopping installers.

Though the antivirus will only target those that it considers threatening to your PC, but sometimes what they consider and what the reality is can differ.

If your Antivirus is stopping the installation of the program, then disabling the antivirus should fix the problem.

To disable Windows Defender, follow the steps given below:

  1. Type Windows Security in the Windows search bar and select the top option.

open-windows-security-from-start-menu

  1. Select the Virus and Threat protection option and then click on the Manage settings option under the Virus and threat protection settings.

manage-virus-and-threat-protection-settings

  1. Disable the Real-time Protection toggle to disable Windows Defender.

disable-real-time-protection

Once the antivirus is disabled, try installing the program and check if the problem arises again.

If the problem still arises, then follow the above steps again to turn on Real-time protection, as the error is most likely not caused by the antivirus.

Solution 9: Disable The User Account Control Feature

Whenever there is a system related change that requires administrator privileges, the User Account Control notifies you about the change.

This feature was included as a way to protect the user, but it is also reported by many users as the cause of this error.

Disabling User Account Control can fix this error. Here is how you can disable it:

  1. Type Change User Account Control settings in the Windows search bar and select the top option.

open-user-account-control-from-start-menu

  1. You will notice a slider on the left side of your screen. Drag that slider down until it says Never notify.
  2. Finally, click on OK to save the changes.

disable-user-account-controll-settings

Solution 10: Delete The Installer And Download It Again

If none of the above solutions worked for you, then the installer file itself may be corrupt. In this scenario, locate the installer file and delete it completely from your computer.

Now, download the installer of the program again from the official website and then try to install the program.

Wrapping Up

So, now you know what to do if you face the error opening file for writing during the installation of any program.

The above solutions should help you fix this issue so read and execute them carefully. And as always, feel free to share your thoughts on this article in the comment section below.

Vim is a popular text editor that has been around for a few decades. It’s commonly included as a standard option to edit text files with most Linux distributions and Mac OS X. Vim is incredibly powerful and flexible – for example, it can work with several files at once through tabs, or easily run automated tasks from inside itself. A huge range of other text editors are introduced from time to time, but Vim has remained a popular option for those wanting more customization and control over their workflow.

One of the most popular error messages that confuses Linux beginners is the “E212: Can’t open file for writing” in vim. The full error log can look like below :

"path/to/example.txt" E212: Can't open file for writing Press ENTER or type command to continue

Code language: PHP (php)

The cause of this error, according to Vim manual, is :

For some reason the file you are writing to cannot be created or overwritten.
The reason could be that you do not have permission to write in the directory
or the file name is not valid.

In this article, we will show you a few ways to fix the “E212: Can’t open file for writing” while working with Vim.

Install vim in Ubuntu

If you see the error message “Command ‘vim’ not found”, it means you don’t have the vim editor installed.

Install vim in Ubuntu

You can install it by running the following command in Ubuntu:

sudo apt-get install vim

Code language: JavaScript (javascript)

Check the file path for its existence

The first thing you need to do is checking the directory or the file path in order to be sure that it does exist. If it doesn’t or one of its parent directory doesn’t, trying to open it with Vim will definitely raise “E212: Can’t open file for writing” error.

In the example below, I’m trying to edit a file in /home/tmp/example.txt but getting “E212: can’t open file for writing” every time I try to save it, as shown in the image below.

In this scenario, you will not be able to create or edit the “example.txt” file inside the /home/tmp directory, as it does not exist.

Now you have two options. You can exit vim , run mkdir tmp to manually create the directory and then start creating the file all over again. Or you can direcly run a command without leaving vim by following the instructions below :

  • Press ESC key to get out of “Please ENTER or type command to continue” prompt.
  • Type !sudo mkdir /home/tmp” followed by Enter key in order to make a new tmp directory inside home. The exclamation mark prefix tells vim to send this command to the system instead of recognizing it as an internal one. Remember to replace /home/tmp/ with your path.
  • Vim now ask for your root password, input it like you usually do when running sudo.

Make sure you have write permission

We’ve seen many users “E212: Can’t open file for writing” error when trying to edit sources.list file. This is because the file you’re trying to edit is placed in a directory where you don’t have the write permission, or have no permission at all. Run the following command to be really sure that this is the case and the destination file is owned by another user :

ls /etc/apt/

Make sure you have write permission

If you’re logged in as a non root account, prefix the command with sudo usually get rid of the problem.

sudo vim /etc/apt/sources.list

Code language: Access log (accesslog)

Check for Read-only filesystem or full disk space

If none of the above solution worked for you, the cause might has something to do with the filesystem or storage capacity.

While being a possible reason, it’s unlikely the storage capacity is the real reason. If it does, you may have seen countless system notifications before you can actually editing anything. But in order to be really sure, run df -h in a terminal and look in the output for 100% use on any mounted path.

The last thing that causes E212 error in Vim is a read-only filesystem. In order to verify if this is the case, run mount command in a terminal. You should find that your device is mounted with rw permission, and not read-only (ro).

If your device is mounted as read-only, run the following command to re-mount it with the correct permission. Remember to replace /mount/point and /partition/identifier with the proper value.

sudo mount -o remount,rw /partition/identifier /mount/point # or sudo mount -o remount,rw /

Code language: Shell Session (shell)

Once the command completes its job, you should be able to edit your files again without encountering “E212: Can’t open file for writing”.

We hope that the information above is useful to you. If you’re interested in a modern source code editor, check out VSCode as well as our guides on how to enable/disable word wrap in VSCode, How to use LaTeX in VSCode or how to automatically indent your code in Visual Studio Code.

Vim can’t open file for writing error is one of the most common and frequent errors you will encounter, if you use Linux and vim editor. Whether you are a novice or Pro Linux user, «E212» is the error code, you don’t like seeing. Most of the time, this error occurs due to insufficient rights or a directory path or file that doesn’t exist, which you are trying to edit. In this post, I will let you know all the reasons and solutions to fix the «Vim can’t open file for writing» error.

When you use Linux, you can get the below-mentioned error, while you try to edit a file —

  • /etc/apt/sources.list» E212: Can’t open file for writing
  • Vim Can’t Save File (E212)
  • Vim can’t open file for writing
  • Root user can’t open file for writing
  • Error in editing vimrc
  • E212: cant open file for writing ec2

Possible causes of the above-mentioned issues —

  • You don’t have access or you are trying to edit a file, which is owned by root user
  • Path of the file, you are trying to edit doesn’t exist (non existing file, non existing directory)
  • Trying to write a network drive and you don’t have access or partial access
  • Trying to edit a read only file system
  • Not enough space exists in your current partition or drive.

Let’s deep dive and fix errors and it’s causes one by one.

Table of Contents

  • 1 Install vim editor in Ubuntu, if not there already
  • 2 How to Fix Vim can’t open file for writing error
  • 3 How to fix etc/apt/sources.list» E212: Can’t open file for writing
  • 4 How to fix even if «Root user can’t open file for writing»
  • 5 Video tutorial
  • 6 Conclusion

Install vim editor in Ubuntu, if not there already

If you get the error: «Command ‘vim’ not found, but can be installed with:» it means you don’t have vim (visual improved) editor installed. Run the following command to install the package in Ubuntu.

$ sudo apt install vim

Install vim in ubuntu using apt install vim command

Solution-1 Check the directory or path of file, create it if it doesn’t exist

First thing first, if you are getting vim can’t open file for writing error, check the path and directory of the file. Let’s understand it from an example.

I am trying to run a command «vim /home/tmp/sample.txt» and getting this error «/home/tmp/sample.txt» E212: can’t open file for writing» while saving it as shown in the image.

vim can't open file for writing

In this scenario, the «tmp» directory inside /home doesn’t exist. So if you will try to either create a new or edit the existing «sample.txt» file. This will not work and you will get errors.

In my case, I need to create the directory tmp inside the /home first to get rid of this "E21: can't open file for writing" error. This may happen in your case also. You may need to create the required directory or maybe you just need to correct the required path :-).

If you want to create a directory without closing the vim editor prompt because you have already edited the file and you don’t want to lose changes. Then follow these steps-

  • Press «ESC» on your keyboard.
  • Type «!sudo mkdir «path of directory that need to be created«. For example, in my case i need to create «tmp» directory inside /home.

E.g.

:!sudo mkdir /home/tmp/

create directory using vim editor

As soon as you will run this command and press enter, It may ask you to give your sudo credentials, and your required directory will get created as shown in the image.

validate directory after creating it from Vim editor

You can edit, save and exit your file now with the «:wq» command without any issue.

How to get the reason of error «E21: can’t open file for writing» using vim help

To find out the reason for the error, follow these steps in the vim editor prompt, where you are getting an error.

  • Press «esc» key on your keyboard
  • Then type :h e212 as shown in image «:h -« represents help and e212 error. Same way you can check for any error, you encountered in vim editor

how to get error help e212 in vim

  • Press enter and you will get the error code and its reason. For example, in my case it is showing the follow —
For some reason the file you are writing to cannot be created or overwritten.
The reason could be that you do not have permission to write in the directory
or the file name is not valid.

/etc/apt/sources.list E212: Can't open file for writing

Press the «ESC» key and then type «:q!» to exit from help.

How to fix etc/apt/sources.list» E212: Can’t open file for writing

If you use Linux, many times in your lifetime. You would have edited the sources.list file and I am sure, you would have encountered an E212 error. Follow solution-2 step by step to fix this issue.

Solution-2 Validate User or file permissions

If you are trying to edit a file and you have given the correct path but still you are getting «can’t open file for writing error«, then you are a victim of permission issues.

If you are logged in with a non-root user, make sure you start with the sudo command, if you are trying to edit a system file or file owned by root.

Let me show you an example, try editing /etc/apt/sources.list with a non-root user and you will understand, what I am trying to prove here.

If you will see the below image, the «sources.list» file is owned by root, so if you will try to edit it using a non-root-user with the following command

$ vim /etc/apt/sources.list

check ther permission of file first, if you are not able to edit the file in vim

You will get «/etc/apt/sources.list» E212: Can’t open file for writing» error.

To fix it, you must edit this file using sudo permissions. run the following command to edit this file successfully.

$ sudo vim /etc/apt/sources.list

How to fix even if «Root user can’t open file for writing»

If you are a root or sudo user, Also you have given the correct path to directory or file but still, you are not able to open the file for writing. Then you are trying to edit a read-only file system or your disk space is full, which doesn’t allow editing and saving a file.

Solution3- Check for Read-only file system or Capacity issue

Use the «df» command to check the partition or disk space usage. If you see «disk» or «partition» available space is showing «0» bytes except for «/dev/loop».

Then make space by deleting or removing unnecessary files using the rm command. It will fix your «vim can’t open file for writing» issue.

$ df -h

check for capacity issue

If you have enough space, then make sure your file system is not mounted as read-only. Run the «mount» command and check for your device, it must be mounted as read-write (rw) not read-only (ro).

For example, /dev/sda5, which is my root (/) partition, mounted as rw.

$ mount

check for file system is read only or read write in ubuntu

If it is showing mounted as read-only in your case, then remount it as rw. If it’s happening due to file system errors, then fix the file system errors and re-mount it to a read-write file system.

$ sudo mount -o remount,rw /partition/identifier /mount/point

or

$ sudo mount -o remount,rw /

You will be able to edit your file, once your file system will be rw and your «vim can’t open file for writing» will vanish.

Video tutorial

Conclusion

I am hopeful, that one of the 3 solutions shared in this post will fix your «E212: Vim can’t open file for writing» error. If you are still facing issues, You can let me know, via your comments. I will try to help you to the best of my knowledge.

The ‘Cannot Open File for Writing‘ error occurs when Windows users attempt to install or update VLC media player. In most cases, the issue occurs on machines that already have or have had VLC Media Player installed at some point.

VLC Media Player Error “Cannot open file for writing”

Most commonly, the ‘Cannot Open File for Writing‘ error is caused by multiple instances of VLC or other applications using LibVLC. To fix this, you can use Task Manager to close any conflicting VLC instance while the installation or updating sequence is taking place. However, some browsers also have the potential to interfere with the legacy way of updating the VLC Media Player application.

And under certain circumstances, some type of system file corruption can be the determining factor why your VLC Media Player installation is no longer able to update.

Method 1: Closing all VLC Instances

As it turns out, the most common cause that will cause the ‘Cannot Open File for Writing‘ error is a situation where multiple VLC instances (or any other applications that are also using LibCLC) are actively running on your machine.

If this scenario is applicable, you can fix the issue swiftly by opening Task Manager and terminating all running instances of applications using LibVLC. Several affected users have confirmed that the issue was resolved as soon as every running instance was closed.

Note: If you don’t want to use Task Manager, you can simply restart your computer and repeat the action that’s currently causing the issue as soon as the next startup is complete.

Here’s a quick guide on closing all VLC instances that might end up causing the ‘Cannot Open File for Writing‘ error:

  1. Close the setup screen where you encounter the error.
  2. Press Ctrl + Shift + Esc to open up Task Manager. Once you’re inside, select the Processes tab from the menu at the top, then scroll down through the list of processes and right-click on the process associated with VLC media player.
  3. Once you see the context menu, click on End Task.
    Ending all associated instances with VLC media player

    Note: If you confirm that no additional instances of VLC Media Player are running, look specifically for other applications that are using LibVLC.

  4. Once every relevant instance is closed, repeat the action that was previously causing the ‘Cannot Open File for Writing‘ error and see if the problem is now resolved.

In case this scenario wasn’t applicable or it didn’t resolve the issue, move down to the next potential fix below.

Method 2: Close all browser instances

One unlikely cause that might contribute to the apparition of the ‘Cannot Open File for Writing‘ error is an installation interference caused by your default browser.

As several affected users have reported, VLC’s ability to update itself can be also interrupted by an open instance of Chrome, Firefox or Brave browser.

If this scenario is applicable, you should be able to fix the issue by using Task Manager to close any active browser instance that might be causing the issue.

Here’s a quick guide on how to close any browser instance in order to resolve the ‘Cannot Open File for Writing‘ error:

  1. Close the setup that is causing the ‘Cannot Open File for Writing‘ error.
  2. Open up a Task Manager instance by pressing Ctrl + Shift + Esc. Once you’re inside Task Manager, choose the Processes tab from the ribbon menu at the top.
  3. Inside the Processes tab, scroll down through the list of active processes, right-click on your active browser instances and choose End Task from the newly appeared context menu.
    Ending the Browser tasks using Task Manager
  4. Once every browser process is closed, repeat the VLC update or VLC installation and see if the problem is now fixed.

In case you’re still encountering the same ‘Cannot Open File for Writing‘ error, move down to the next method below.

Method 3: Running SFC and DISM scans

As it turns out, the issue can also occur due to some kind of System File Corruption that ends up affecting your operating system’s ability to install new software. If this scenario is applicable, you should be able to fix the issue by running a couple of native utilities (DISM and SFC) that were designed to find, fix or replace corrupted instances.

Although the two utilities have similar functionality, they do things differently. For example, DISM (Deployment Image Servicing and Management) relies heavily on a subcomponent of WU to replace corrupted data with healthy equivalents.

On the other hand, SFC (System File Checker) is an entirely local tool that uses locally cached data to fetch healthy files when corrupted instances are found.

Since both utilities have their own strong suits, we recommend that you run both in quick succession in order to maximize your chance of resolving the ‘Cannot Open File for Writing‘ error:

  1. Press Windows key + R to open up a Run dialog box. Next, type ‘cmd’ inside the text box, then press Ctrl + Shift + Enter to open up an Elevated Command Prompt. If you get prompted by the User Account Control (UAC), click Yes to grant admin access.
    Running Command Prompt
  2. Once you manage to get inside the elevated CMD prompt, type the following command and hit Enter to initiate an SFC scan:
    sfc / scannow

    Note: It’s very important that you don’t interrupt this process once you get this started. Doing this might create bad sectors that might facilitate the apparition of similar issues in the future.

  3. After the scan is complete, restart your computer once again and wait for the next startup to complete.
  4. Once your computer boots back up, follow step 1 once again to open up another elevated CMD prompt. When you return to the elevated CMD window, type the following command below to initiate a DISM scan:
    dism /online /cleanup-image /restorehealth

    Note: To complete this scan without issues, you will need to ensure that your Internet connection is stable. This is important because DISM uses WU to download healthy copies for broken systems that need to be replaced. If you get a DISM error when you try to launch the utility, here’s how to fix it.

  5. As soon as the operation is complete, reboot your computer once again and see if the issue is resolved at the next startup.

Photo of Kevin Arrows

Kevin Arrows

Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

«I am trying to edit sources.list using vi editor but getting the following error while saving the file:

/etc/apt/sources.list» E212: Can’t open file for writing» — from Stack Overflow

can't open file for writing in Vim

If you’re a Linux user using Vim, you may have encountered the following error while trying to write to a file: E212 can’t open file for writing. This article will show you three ways to fix this error. All of these methods work in Ubuntu and other Debian-based distributions. Let’s get started!

Workable Solutions Step-by-step Troubleshooting
1. Check File Permissions Edit the «sources.list» file using a non-root-user with the following command…Full steps
2. Check the File Lock Find the file with this command: lsattr /home/admin/$filename…Full steps
3. Fix Read-only File System Check the disk space with this command. $ df -h. Then, make space by deleting…Full steps

Reasons — E212 Can’t Open File for Writing

This problem can be caused by many things, from a permissions issue to low disk space. In this part, we’ll analyze the reasons. Let’s get started!

When using the vi command to modify the content of a Linux file, it is found that it cannot be saved. Every time you finish writing, you can use the «:q!» command to exit normally. However, when you use the «:wq!» command to save the file and exit, these error messages prompt:

  • Vim Can’t Save File (E212)
  • Vim can’t open file for writing
  • Root user can’t open file for writing
  • /etc/apt/sources.list» E212: Can’t open file for writing
  • E212: Can’t open file for writing. Press ENTER or type command to continue

You receive this error for two main reasons:

  • The current user has insufficient permissions.
  • This file may be in use by other programs or users.

Solutions — 3 Ways to Fix Can’t Open File for Writing in Vim

E212: can’t open file for writing is an error that can occur when trying to save a file in Vim. There are a few different ways to fix this error, depending on the cause. 

Method 1. Validate User and Check File Permissions

The general cause of the error is the permission issue. The solution is to add sudo in front of the file to temporarily provide administrator privileges when using the vi command to open the file. For example, use the command «sudo vi hosts» to open and edit the file.

Step 1. Edit the «sources.list» file using a non-root-user with the following command.

$ vim /etc/apt/sources.list

Step 2. Get «/etc/apt/sources.list» E212: Can’t open file for writing» error.

Step 3. Run sudo permissions to fix the error.

$ sudo vim /etc/apt/sources.list

Validate user and check file permissions to fix can't open file for writing in Vim

Method 2. Check If the File Is Locked to Fix Can’t Open File for Writing

If you are a root or sudo user, but you still can’t open the file for writing. Then, you can try to exit the file and check if the «I» command locks it.

check the lock to fix can't open file for writing in Vim

Step 1. Find the file with this command:

lsattr /home/admin/$filename

Step 2. Check the I lock.

If there is an «I» displayed, the file is locked. You can execute this command to unlock your files.

chattr -i $filename

After this, execute q! to exit the file. When viewing the file again, it is found that the content has been changed and saved.

Method 3. Check for Read-only File System or Capacity Issue

You still face this error if you have permission and use the sudo command. Then, you need to check for a read-only file system or capacity issue.

Step 1. Check the disk space with this command.

$ df -h

check read-only file system to fix can't open file for writing in Vim

Step 2. Then, make space by deleting or removing unnecessary files using the rm command.

Step 3. Run mount command to check for your device. It must be mounted as read-write (rw) not read-only (ro).

$ mount

Step 4. Fix the file system errors and re-mount it to a read-write file system.

$ sudo mount -o remount,rw /partition/identifier /mount/point

or

$ sudo mount -o remount,rw /

Then, you have resolved the «E212: Vim can’t open file for writing» error. You can watch this video to get help if you still have problems.

  • 0:17 fix can’t open file for writing while using Vim
  • 0:50 make sure the path
  • 2:57 check the file permission

How to Recover Lost Linux Files with Software

What if you lost data after fixing the «E212: Vim can’t open file for writing» error? Don’t worry. EaseUS Data Recovery Wizard is a helpful tool for recovering lost data on Linux systems. It has a simple interface that makes it easy to use, even for those who need to become more familiar with data recovery programs.

  • EaseUS Data Recovery Wizard can recover deleted files from any storage device, including hard drives, USB flash drives, and memory cards.
  • It also supports various file types, such as photos, videos, documents, and emails.
  • Best of all, EaseUS Data Recovery Wizard is very easy to use. This makes it an excellent choice for anyone who needs to recover lost data on a Linux system.

Download this software and find files in Linux.

Step 1. Install and Launch EaseUS Data Recovery Wizard on your Windows PC. Choose «Linux Recovery» on the left panel. 

Step 2. This software will detect your IP and Port automatically. You need to input the user name and password. If the IP address or Port is not right, you can correct it manually. Then, click «Connect Now». 

choose linux recovery

Step 3. After successfully connecting to your Linux device, EaseUS recovery software will start scanning the disk to find all lost and deleted files. When the scan process completes, click «Filter» > «Type» to specify lost file types.

choose the recovered data type

Step 4. You can preview the scanned files first. Then, select the target data and click the «Recover» button to restore lost files in Linux. 

recover windows 10 lost data

Conclusion 

Follow the solutions above to fix the «can’t open file for writing» error in Vim without losing data. If you have any questions or need help, feel free to reach out and contact us. We’re here to help!

Can’t Open File for Writing FAQs

Read the questions and answers below to get additional help.

1. What to do if you are faced with the action can’t be completed error?

To fix the action can’t be completed because the file is open:

  • Run File Locksmith
  • Stop Processes with Task Manager
  • Empty the Recycle Bin and Restart
  • Restart Windows Explorer
  • Delete Temp Files

2. How do you fix cannot open file for writing in Vim?

You can fix the can’t open file for writing in three ways:

  • Check File Permissions
  • Check If the File Is Locked
  • Check for Read-only Memory

3. How to exit Vim in the terminal without saving?

To exit Vim without saving changes:

  • Switch to command mode by pressing the Esc key.
  • Press : (colon) to open the prompt bar in the bottom left corner of the window.
  • Type q! after the colon and hit Enter to exit without saving the changes.

4. What is Vim used for?

Vim is a highly configurable text editor built to enable efficient text editing. It is an improved version of the vi editor distributed with most UNIX systems.

Vim – это текстовый редактор, используемый в операционных системах Linux, который помогает создавать и обновлять различные текстовые файлы с разными расширениями. Иногда, когда вы пытаетесь создать файлы с помощью утилиты Vim, вы получали ошибку: “Vim can’t open file for writing”. Причин этой ошибки может быть несколько.

Предпосылки:

На вашем компьютере должен быть установлен и настроен дистрибутив Linux. В нашем случае у нас есть дистрибутив Linux Ubuntu 20.04. С другой стороны, у вас должны быть права sudo для использования системы Linux и утилиты Vim.

Установка Vim:

В самом начале вы должны убедиться, что в вашем дистрибутиве Linux установлена ​​утилита Vim. Для этого мы сначала проверим это в нашей системе. Следовательно, вы должны открыть терминал командной строки из панели действий на рабочем столе Linux. После этого выполните приведенную ниже команду Vim, чтобы получить информацию о Vim. Как показано на изображении, в нашей Ubuntu 20.04 не установлена ​​утилита Vim. Он также предлагает некоторые инструкции по установке Vim в системе. Используйте один из них для установки Vim.

$ vim

Теперь наша очередь установить Vim в нашей системе Linux. Итак, для этого мы должны использовать команду sudo apt. Попробуйте выполнить команду ниже, чтобы установить его в вашей системе. Для инициализации процесса установки потребуется пароль вашей учетной записи root. Введите свой пароль sudo и нажмите кнопку «Enter», чтобы продолжить. Вы увидите, что он начнет установку и загрузку утилиты Vim вместе с другими пакетами.

$ sudo apt install vim

Во время установки он будет приостановлен, и появится вопрос. Система предложит вопрос для подтверждения действия по установке, в котором говорится: “Do you want to continue? [Y/n] “. Если вы хотите продолжить процесс установки Vim, вам нужно нажать «y» и нажать Enter, в противном случае нажмите «n» и нажмите кнопку «Enter». Итак, мы нажали «Y» и нажали клавишу Enter, чтобы продолжить установку редактора Vim в Ubuntu 20.04. Это запустит правильную установку редактора Vim. Вам нужно подождать некоторое время, пока он не завершит свой процесс.

После установки Vim вы можете проверить информацию о нем, используя ту же команду, что и ниже.

$ vim

Если ваша система Linux успешно откроет окно, показанное ниже, как показано на прикрепленном снимке, вы можете использовать редактор Vim.

Ошибка устранения неполадок. Vim не может открыть файл для записи

Получите ошибку:

Теперь мы создадим файл с помощью команды Vim в командной оболочке. Мы создадим этот файл в любом из каталогов. Итак, попробуйте следующую команду Vim, чтобы создать файл «smtpd.conf» в каталоге, указанном ниже.

$ vim /usr/lib64/sas12/smtpd.conf

Откроется окно, показанное ниже, в котором путь и имя файла указаны в нижней части нижнего заголовка. Пора записать содержимое этого файла по заданному пути.

Чтобы записать содержимое файла и выйти из редактора Vim, попробуйте следующую команду «wq» со знаком двоеточия «:», затем нажмите кнопку Enter, чтобы запустить эту команду.

Сразу после того, как вы нажмете кнопку «Enter», вы получите сообщение об ошибке: “E212: Can’t open file for writing”, как показано на изображении ниже. Для продолжения нажмите кнопку «Enter». Ошибка устранения неполадок. Vim не может открыть файл для записи

Чтобы проверить причину этой ошибки, нам нужно написать еще одну инструкцию в редакторе Vim. Попробуйте выполнить следующую команду sudo в редакторе Vim, начиная с ключевого слова «:w», заканчивая ключевым словом «tee» и знаком процента. Нажмите клавишу «Enter», чтобы увидеть причину ошибки.

:w ! sudo tee %

Для записи содержимого файла и сохранения файла по указанному пути требуется пароль вашей учетной записи sudo. Введите свой корневой пароль и нажмите кнопку «Enter». Вывод показывает, что в вашей системе Linux нет такого файла или каталога. Это означает, что мы указываем причину этой ошибки. Снова нажмите клавишу «Enter», чтобы продолжить работу с Vim. Напишите приведенную ниже команду выхода и нажмите клавишу «Enter», чтобы вернуться в оболочку терминала.

Мы узнали о причине ошибки, которая заключается в том, что указанный путь не был фактически создан. Вы также можете проверить путь в командной строке с помощью команды ls. Вывод показывает, что такой каталог не создается.

$ ls /usr/lib64/sas12

Устранить ошибку:

Во-первых, мы должны создать путь или каталог в оболочке командной строки. Чтобы создать каталог, указанный в указанном выше пути, мы должны использовать команду mkdir вместе с флагом «-p». Если вы используете команду mkdir без ключевого слова «sudo», это может быть вызвано исключением «Permission denied».

$ mkdir –p /usr/lib64/sas12

Давайте попробуем эту команду с ключевым словом «sudo», и вы увидите, что она работает нормально.

$ sudo mkdir –p /usr/lib64/sas12

Снова напишите команду Vim, а затем укажите путь к файлу, чтобы проверить изменения. Откроется редактор Vim.

$ vim /usr/lib64/sas12/smtpd.conf

Когда вы напишете приведенную ниже команду sudo, для продолжения может потребоваться пароль вашей учетной записи sudo. Вы можете увидеть, что после ввода пароля и нажатия кнопки «Enter» будет выдано предупреждение. Вы должны нажать клавишу «L», а затем кнопку «Enter», чтобы загрузить этот файл в указанную папку.

:w !sudo tee %

Он загрузит файл и предоставит ему права только для чтения. Нажмите клавишу Enter.

Теперь, когда вы вводите команду «wq», она будет работать нормально.

Заключение:

Мы сделали решение ошибки: “Vim can’t open file for writing” в мгновение ока. Надеюсь, вы сможете решить эту ошибку с удобством.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

0 Пользователей и 1 Гость просматривают эту тему.

  • 7 Ответов
  • 6888 Просмотров

Пытаюсь обновиться с 3.3.3 до 3.4.8, способ установки — Записывать файлы напрямую, выходит ошибка «Cannot open file for writing log». На просторах интернетов нашёл совет:

1. Установить права 777 на папку /logs в Joomla 3.

2. Получить временно права на запись файла configuration.php (после редактирования вернуть родные 444).
Кстати у меня на него 644, может стоит поставить 444?

Не помогает, та же ошибка. Подскажите пожалуйста в чём ещё может быть причина?

« Последнее редактирование: 02.02.2016, 17:40:56 от b2z »

Записан

скорее всего не верные пути, напишите сюда из файла configuration.php строки

public $log_path
public $tmp_path

Записан

Эта подпись отображается внизу каждого Моего сообщения. Я также могу использовать BB код и смайлы.

Точно, при переезде с хостинга на хостинг забыл поменять
старые пути /home/u385377/ИМЯ_САЙТА/www/logs’
диспетчер файлов показывает что сейчас всё лежит в
/var/www/alco/data/www/ИМЯ_САЙТА/logs
Указать полностью?
Ну и для tmp соответственно.

Записан

Эта подпись отображается внизу каждого Моего сообщения. Я также могу использовать BB код и смайлы.

Вернул права на то что было изначально, изменил пути — та же ошбка.
Изменил права опять на 777 — появилось сообщение: Ошибка загрузки пакета обновления
Так, небольшое продвижение вперёд )

« Последнее редактирование: 02.02.2016, 02:48:43 от Vindy »

Записан

Права не надо трогать, только для того чтобы внести изменения, всегда 644 или 444.

Незнаю что такое может быть, по идее, в папку tmp как раз таки должен загружать..

Записан

Эта подпись отображается внизу каждого Моего сообщения. Я также могу использовать BB код и смайлы.

Чорд, к Логам права дал а к Темпу забыл
В итоге как раз изменение прав к Темпу дало дальнейший результат
Были к каталогу 755, в нём index.html и pkg_xmap.xml с 644. Не мудрствуя дал и к нему и к содержимому 777.

Появилось окно
Подождите, Joomla! обновляется…
с прогрес баром и всем что пологается
Но в центре

ERROR
Invalid login

В каталоге Темп появился Joomla_3.4.8-Stable-Update_Package.zip

В итоге победил изменением прав. Поменял права на папку с сайтом, все подпаки и файлы на 777.
Обновление прошло успешно. Затем вернул как было, все папки 755, все файлы 644.

Понравилась статья? Поделить с друзьями:
  • Error cannot load recovery img что делать
  • Error cannot load recovery img twrp
  • Error cannot load message class for
  • Error cannot load from mysql proc the table is probably corrupted
  • Error cannot install in homebrew on arm processor in intel default prefix usr local