Problem copying the file with the following error code 5

New Page

How to fix CopyFile() error 5 – access denied error

Pregunta

Preguntó hace 5 years, 2 months

Modified 3 years, 4 months ago

Visto 6k times

Reportar este anuncio

Esta pregunta muestra el esfuerzo de investigación; it is useful and clear

2

This question shows no research effort; it’s not clear or not helpful

1

Bookmark this question.

View activity on this post.

Try writing an archive copy function that you can use on both Linux and Windows. Works on Linux, for Windows detects error code 5 intending to use WinApi CopyFile() function.

En el encabezado Archivo.h

Esta is the personalized function defined in the space of file numbers that debería can use both in Linux and in Windows.

class File { public: static bool copyFile(std::string source, std::string destination); private: }

In Archivo.cpp

For Linux it’s simple:

#ifdef __unix__ #include “File.h” bool File::copyFile(std::string source, std::string destination) { std::string arg = source + ” ” + destination; return launchProcess(“cp”, arg); } #end if

Blocking Windows specific code, use WinAPI’s CopyFile() function (#include <windows.h>). Esto acepta tipos de datos LPCWSTR en lugar de padlock. To superar esto, it created a function that converts padlock to LPCWSTR types.

#ifdef _WIN32 #include “File.h” #include <Windows.h> std::wstring strtowstr(const std::string &str) { // Convert an ASCII string to a Unicode string std::wstring wstrTo; wchar_t *wszTo = new wchar_t[str.length() + 1]; wszTo[str.size()] = L’\0′; MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo,(int)str.length()); wstrTo = wszTo; remove[] wszTo; return wstrTo; } bool File::copyFile(std::string source, std::string destination) { std::wstring wsource = strtowstr(source); std::wstring wdestination = strtowstr(destination); int result = CopyFileW(wsource.c_str(), wdestination.c_str(), TRUE); //for debugging… std::wcout << “The error is ” << GetLastError() << std::endl; std::wcout << wsource.c_str() << std::endl; std::wcout << wdestination.c_str() < <std::endl; if (result == 0) { returns false; } returns true; } #end if

In my prueba program

TEST(all,main_copy_file) { std::cout << “Testing the copyFile() function…” << std::endl; std::string srcDir = File::currentWorkingDirectory() + “srcDir”; File::makeDirectory(srcDir); std::string destDir = File::currentWorkingDirectory() + “destDir/”; File::makeDirectory(destDir); File::makeFile(srcDir, “testFile”, “.txt”); ASSERT_TRUE(File::fileExists(srcDir + “/testFile.txt”)) << “Error: The test file was not generated” << std::endl; ASSERT_TRUE(File::directoryExists(destDir)) << “Error: destination directory does not exist” <<std::endl; ASSERT_TRUE(File::copyFile(srcDir + “/testFile.txt”, destDir)) << “Error: Copy failed” << std::endl; ASSERT_TRUE(File::

When exiting the application (in Windows)

/* Test copyFile() function… Error is 5 C:\GIT\CorteX\Externals\OSAL\build\Debug/srcDir/testFile.txt C:\GIT\CorteX\Externals\OSAL\build\ Debug/destDir/error: Value of: File::copyFile(srcDir + “/testFile.txt”, destDir) Real: false Expected: true Error: Copy not successful */

Error code 5 is an access denied error. I think it gives this error when the directory doesn’t exist, the directory is open elsewhere, or I don’t have the permissions.

Since I tested that the directory exists, I think it must be one of the last two. I may only have restricted admin rights (I don’t know), but I can paste in the “destDir” without admin permission. So maybe he thinks the directory is open? Is there a command to make sure the directory is closed?

The test is passed when running on Linux.

  • c++
  • the Windows
  • winapi
  • copy

To share

Share a link to this question

Copy link CC BY-SA 3.0

Follow

Follow this question to receive notifications

modified on July 14, 2017 at 3:11 PM

Blue7

requested on July 14, 2017 at 2:15 p.m.

Blue7 user avatar

Blue7 Blue7

1,572 4 4 gold badges 24 24 silver badges 47 47 bronze badges

ten

  • 1

    notez que C++ propose déjà des fonctions pour copier des fichiers.

    – Le Techel

    14 juil. 2017 à 14:16

  • Pouvez-vous m’orienter vers une/certaines de ces fonctions ?

    – Bleu7

    14 juil. 2017 à 14:20

  • 2

    vous n’avez aucune autorisation. si quelqu’un d’autre ouvre le dossier avec un accès exclusif – ce sera une autre erreur – ERROR_SHARING_VIOLATION, si le fichier/dossier n’existe pas – ce sera encore une autre erreur. aussi cette erreur dans le cas où le fichier existe déjà et en lecture seule

    – RbMm

    14 juil. 2017 à 14:20

  • 1

    @Blue7 en.cppreference.com/w/cpp/filesystem/copy

    – Le Techel

    14 juil. 2017 à 14:20

  • @RbMm Do you have any guesses on why I do not have permissions? I am only trying to copy a file from one directory to another. Both of the files are in directories that are inside the current working directory, so I shouldn’t have a problem, should I?

    –  Blue7

    Jul 14, 2017 at 14:24

 |  Show 5 more comments

2 Answers 2

Sorted by: Reset to default

Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first)

This answer is useful

2

This answer is not useful

Show activity on this post.

The CopyFile API expects file names for both source and destination files. Your code passes a directory name for the destination. This causes the API to fail. You need to append the file name for the destination as well.

Besides that, there are several other issues with your code:

  • The path separator on Windows is a backslash (\). Your are mixing forward slashes (/) and backslashes. Depending on the arguments passed, the system won’t translate forward slashes to backslashes, before passing them on to lower-level file I/O API’s.
  • You are calling GetLastError too late. You need to call it immediately, whenever it is documented to return a meaningful value. Do not intersperse it with any other code, however trivial it may appear to you. That code can modify and invalidate the calling thread’s last error code.
  • Your code assumes ASCII-encoded strings. This will stop working, when dealing with files containing non-ASCII characters. This is quite common.
  • new wchar_t[…] buys you nothing over std::vector<wchar_t>, except the possibility to introduce bugs.
  • Your MultiByteToWideChar-based string conversion implementation makes (undue) assumptions about the code unit requirements of different character encodings. Those assumptions may not be true. Have the API calculate and tell you the destination buffer size, by passing 0 for cchWideChar.
  • Your string conversion routine ignores all return values, making bugs ever so likely, and unnecessarily hard to diagnose.

Share

Share a link to this answer

Copy link CC BY-SA 3.0

Follow

Follow this answer to receive notifications

answered Jul 15, 2017 at 7:55

IInspectable user avatar

IInspectable IInspectable

42.6k 8 8 gold badges 79 79 silver badges 166 166 bronze badges

Add a comment  | 

Report this ad

This answer is useful

0

This answer is not useful

Show activity on this post.

I know this is an old post, but for anyone who stumbles here needing more help:

CopyFile has the following constraints which if not met can give access denied error:

  1. Insufficient permissions for the current user
  2. File is in use
  3. Filepath is a directory and not a file
  4. File is read-only

In my case all the above were met, still I kept getting the same error. What helped me was a simple SetFileAttributes(filePath,FILE_ATTRIBUTE_NORMAL)

Retrieving and Changing File Attributes

SetFileAttributes

Share

Share a link to this answer

Copy link CC BY-SA 4.0

Follow

Follow this answer to receive notifications

answered May 29, 2019 at 20:12

labmat user avatar

labmat labmat

193 1 1 gold badge 1 1 silver badge 10 10 bronze badges

Add a comment  | 

Your Answer

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid …

  • Asking for help, clarification, or responding to other answers.
  • Make statements based on opinion; back them up with references or personal experience.

To learn more, check out our tips for writing great answers.

Saved Draft

Draft rejected

Sign up or log in

Sign up with Google

Sign up using Facebook

Sign up using your email and password

Submit

Post as guest

Last name

E-mail

Required, but never displayed

Post as guest

Last name

E-mail

Required, but never displayed

Post your answer Ignore

By clicking “Post your answer” you agree to our Terms of Service, Privacy Policy and Cookies Policy

Not the answer you are looking for? Browse other tagged questions

  • c++
  • the Windows
  • winapi
  • copy

or ask your own question.

  • The overflow blog
  • Tendances Stack Overflow : activité du site en semaine par rapport au week-end

  • Ne laissez pas les logiciels vous voler votre temps (Ep. 491)

  • Présenté sur Meta
  • Modifications récentes du contraste des couleurs et mises à jour d’accessibilité

  • Réviseur par-dessus bord ! Ou une demande d’amélioration des conseils d’intégration pour les nouveaux…

  • Collectives Update: Recognized Members, Articles, and GitLab

  • Should I explain other people’s code-only answers?

Report this ad

Hot Network Questions

  • My government (China) cancelled my passport. I’m in Malaysia, what can I do?
  • Can I work remotely for a non-Singapore employer while visiting Singapore?
  • What makes a game unmoddable?
  • Mapping Diagram with Parallelograms
  • Cooking (not baking) adjustments for altitude
  • Are these two sentences equivalent? 「トイレはあそこです。」、「あそこはトイレです。」
  • Why can’t you say “A doll was made me by my sister”?
  • How to indicate to the user that they haven’t completed a prerequesite?
  • Ripple voltage filtering capacitor
  • Solution of a recurrence relation
  • Is the title and cypher of a monarch modified if the Queen has the same name as her predecessing king?
  • How do I solve this sudoku without guessing
  • AIC for nested models: is the AIC of a smaller model A always smaller than that of the nesting model B?
  • En el inglés moderno temprano, ¿hay ejemplos de la construcción progresiva “a- + gerundio” donde el gerundio comienza con una vocal?
  • ¿Debo seguir mi propia dirección para mi investigación de doctorado?
  • ¿Cómo navegan por el aeropuerto JFK las personas que no hablan inglés?
  • ¿Qué sucede cuando Gideon, The Oathsworn muta?
  • Manera fácil y económica de absorber más de 5 A de una fuente de alimentación
  • ¿Por qué el condensador de derivación no provoca un cambio de fase en este circuito oscilador?
  • Un compañero de trabajo siempre me pide que haga cosas pequeñas cuando no son mi responsabilidad
  • Vaguedad en lugar de especificidad cuando los riesgos son enormes
  • ¿Cómo deshacerse de una gran cantidad de azúcar húmedo?
  • Cuando Artemis se queda sin retrocesos
  • ¿Es bueno mi hechizo casero Hiccupera?

Feed de preguntas

Suscríbete a RSS

Feed de preguntas

Para suscribirse a esta fuente RSS, copie y pegue esta URL en su lector de RSS.

Cómo corregir el código de error 5 (ERROR_ACCESS_DENIED)

Última modificación el 14/02/2020 5:44 p. m. EST

Error code 5 is a Windows error code that appears when the user does not have sufficient permissions to access the archive or the requested location. Aparece cuando al software se le negó el acceso a una ubicación con el fin de guardar, copier, abrir o cargar archivos. It is only possible to access any Windows user account without having administrative privileges where you intend to access a red carpet location that is protected by Windows user security control policies. Este error puede aparecer cuando intenda buscar una ubicación, guardar un archivo o uncargar un archivo. This error can also reveal the intention to eject the Buscar actualizaciones function , que descarga un instalador para actualizar el software.

If you find the code of error 5, try the following:

  • Asegúrese de haber iniciado session en Windows con una cuenta de usuario que tenga permiso para acceder a la ubicación. In the case of downloading updates, you will need to make sure that your user account permits permission to keep the files in the software installation mat (usually C:\Program Files (x86)\GoFiler Complete or a mat in C: \Program Files ( x86) with software su count). If su cuenta de usuario no tiene permiso para acceder à la ubicación, comuníquese con el departamento de TI de su organización o ejecute el proceso con privilegios elevados.

Nuestro equipo de soporte puede ayudarlo a identificar este problema, pero no podemos resolverlo directamente por usted. This error usually indicates an ambient problem that the IT department debería solved.

Related Articles

  • How to Fix Error Code 3 (ERROR_PATH_NOT_FOUND)

  • How to decipher error codes

  • Understanding XBRL Calculations

  • How do I add new default templates to the Project Wizard?

  • Fixed empty element names

How would you rate this article?

Thank you for your opinion!

User icon

Last name

E-mail

Submit

Thanks! Your comment has been submitted for approval.

Error 5: Windows 10/11 Access Denied Error [Complete Solution]

by Matthew Adams

Matthew Adams Matthew Adams

Matthew Adams

Windows and software expert

Matthew is a freelancer who has produced a variety of articles on various technology-related topics. Su enfoque principal es el operating system Windows y all the cosas… read more

Updated on August 26, 2022

Affiliate Disclosure

4

Cuota

X


Video Problem copying the file with the following error code 5

Related Posts

Free chat room code for my website

Contents1 How to set up a free chat room on the website.2 3 comentarios2.1 Trackbacks/Pingbacks2.2 Submit a Comment Cancel reply3 How to Create a Chat Room Website…

Background image full screen css

Contents1 Cómo – Full Page Image1.1 Example1.2 Example2 CSS background image tamaño tutorial: how to codify a complete page background image3 Perfect Full Page Background Image3.1 Méthode CSS géniale,…

WordPress leverage browser caching

Contents1 Aproveche el almacenamiento in hidden del navegador1.1 Will it works for my website?1.2 Where are plugin options1.3 Some JavaScript files still display under Leverage Browser Caching1.4…

WordPress post to facebook page

Contents1 How to Automatically Post to Facebook from WordPress1.1 Download Now: How to Launch a WordPress Website [Free Guide + Checklist]1.2 1. Create an IFTTT account.1.3 2….

Download images from wordpress media library

Contents1 How to export your WordPress media library1.1 Download maintenant : How to launch a WordPress website [Free Guide + Checklist]1.2 How to export your WordPress media…

WordPress single post template

Contents1 How to Create Custom Unique Post Templates in WordPress2 Post Template Files2.1 author.php2.2 Fecha.php3 Handbook navigation4 How to Create Custom Single Post Templates in WordPress5 Video…