Rename a txt file in C ++

1

I am programming in visual c ++ 2008 for smart device. I am trying to change the name of a txt file. I have a code taken from Microsoft msdn but it does not work for me. The code compiles well and does not give any errors, but does not change the file name. Any ideas? Thanks.

#include "stdafx.h"
#include <stdio.h>
#include <wchar.h>

int _tmain(void)
{
char oldname[] = "alarm.txt";
char newname[] = "prueba.txt";
int _wrename( wchar_t *oldname, wchar_t *newname);
return 0;
}

This is the link: link

I have also tried this way but it does not work either.

#include "stdafx.h"
#include <cstdio>
#include <wchar.h>
#include "Windows.h"

int _tmain(void)
{
char oldname[] = "alarm.txt";
char newname[] = "prueba.txt";
_wrename(oldname, newname);
return 0;
}

I get this error: Error 1 error C3861: 'wrename': no se encontró el identificador c:\Users\P\Documents\Visual Studio 2008\Projects\Rename a file C++ AML\Rename a file C++ AML\Rename a file C++ AML.cpp 13 Rename a file C++ AML

    
asked by Andermutu 27.07.2017 в 09:49
source

2 answers

3

wchar_t no is equivalent to char . In wchar_t a character can occupy more than 1 byte.

with char you have to use rename :

int _tmain()
{
  const char oldname[] = "alarm.txt";
  const char newname[] = "prueba.txt";
  rename(oldname, newname);
  return 0;
}

To call _wrename you have to use wchar_t :

int _tmain()
{
  const wchar_t oldname[] = L"alarm.txt";
  const wchar_t newname[] = L"prueba.txt";
  _wrename(oldname, newname);
  return 0;
}
    
answered by 27.07.2017 в 10:28
3

There must be a reason why you do not rename the file, the function you are using can report the following errors:

  • EACCES the file or directory specified by newname already exists or can not be created (invalid path); u oldname is a directory and newname specifies a different route.
  • ENOENT the file or path specified by oldname has not been found.
  • EINVAL the name contains invalid characters.

To check if the renaming function returns an error, you should check if the return is not 0 :

const char oldname[] = "alarm.txt";
const char newname[] = "prueba.txt";

if (rename(oldname, newname))
{
    std::cout << "La operacion ha fallado con codigo " << errno << '\n';
}

In the previous code, if the function returns something other than 0 , it will be considered that if is true and will show you the error code, here you can see a list of the error codes.

  

I get this error: Error 1 error C3861: 'wrename': no se encontró el identificador c:\Users\P\Documents\Visual Studio 2008\Projects\Rename a file C++ AML\Rename a file C++ AML\Rename a file C++ AML.cpp 13 Rename a file C++ AML

The error complains about wrename and you are using the code _wrename sure that you are hitting the same code that gives you the error?

    
answered by 27.07.2017 в 10:41