rename function in C - GeeksforGeeks (2024)

Skip to content

rename function in C - GeeksforGeeks (1)

Last Updated : 21 Sep, 2023

Summarize

Comments

Improve

Suggest changes

Like Article

Like

Save

Report

The rename() function is used to rename a file in C. It changes the name of the file from old_name to new_name without modifying the content present in the file. It is defined inside <stdio.h> header file.

In this article, we will learn how to rename a file using the rename() function in C programming language.

Syntax of rename()

int rename (const char *old_name, const char *new_name);

If new_name is the name of an existing file in the same folder then the function may either fail or override the existing file, depending on the specific system and library implementation.

Parameters

  • old_name: String that represents the name of an existing file to be renamed.
  • new_name: String containing the new name of the file.

Return Value

The return type of the function is an integer.

  • If the file is renamed successfully, zero is returned and it prints a success message.
  • On failure, a nonzero value is returned and it prints an error message using perror().

Example of rename()

Assume that we have a text file having the name geeks.txt, having some content. So, we are going to rename this file, using the below C program present in the same folder where this file is present.

rename function in C - GeeksforGeeks (3)

C Program to Demonstrate the use of rename() Function

C

// C program to demonstrate use of rename()

#include <stdio.h>

int main()

{

// Old file name

char old_name[] = "geeks.txt";

// Any string

char new_name[] = "geeksforgeeks.txt";

int value;

// File name is changed here

value = rename(old_name, new_name);

// Print the result

if (!value) {

printf("%s", "File name changed successfully");

}

else {

perror("Error");

}

return 0;

}

Output

If file name changedFile name changed successfully ORIf file is not presentError: No such file or directory

rename function in C - GeeksforGeeks (4)



Please Login to comment...

Similar Reads

C Function Arguments and Function Return Values

Prerequisite: Functions in C A function in C can be called either with arguments or without arguments. These functions may or may not return values to the calling functions. All C functions can be called either with arguments or without arguments in a C program. Also, they may or may not return any values. Hence the function prototype of a function

6 min read

error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++

Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th

9 min read

Difference between virtual function and inline function in C++

Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th

2 min read

Difference Between Friend Function and Virtual Function in C++

A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and

3 min read

What happens when a virtual function is called inside a non-virtual function in C++

Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &amp;lt;iostream&amp;gt; using namespace std; class Base { public: void print() { cout &amp;lt;&amp;lt; &amp;quot;Base class print function \n&amp;quot;; } void invoke() { cout &amp;lt;&amp;lt; &amp;quot;Base class invoke function \n&amp;quot;;

2 min read

Function Overloading vs Function Overriding in C++

Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code

3 min read

Difference between Virtual function and Pure virtual function in C++

Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu

2 min read

Write a one line C function to round floating point numbers

Algorithm: roundNo(num) 1. If num is positive then add 0.5. 2. Else subtract 0.5. 3. Type cast the result to int and return. Example: num = 1.67, (int) num + 0.5 = (int)2.17 = 2 num = -1.67, (int) num - 0.5 = -(int)2.17 = -2 Implementation: /* Program for rounding floating point numbers */ # include&lt;stdio.h&gt; int roundNo(float num) { return nu

1 min read

Does C support function overloading?

First of all, what is function overloading? Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures. This feature is present in most of the Object Oriented Languages such as C++ and Java. But C doesn't support this feature not because of OOP, but rather because

2 min read

How can I return multiple values from a function?

We all know that a function in C can return only one value. So how do we achieve the purpose of returning multiple values. Well, first take a look at the declaration of a function. int foo(int arg1, int arg2); So we can notice here that our interface to the function is through arguments and return value only. (Unless we talk about modifying the glo

2 min read

How to declare a pointer to a function?

While a pointer to a variable or an object is used to access them indirectly, a pointer to a function is used to invoke a function indirectly. Well, we assume that you know what it means by a pointer in C. So how do we create a pointer to an integer in C? Huh..it is pretty simple... int *ptrInteger; /*We have put a * operator between int and ptrInt

2 min read

Can We Call an Undeclared Function in C++?

Calling an undeclared function is a poor style in C (See this) and illegal in C++and so is passing arguments to a function using a declaration that doesn't list argument types.If we call an undeclared function in C and compile it, it works without any error. But, if we call an undeclared function in C++, it doesn't compile and generates errors. In

2 min read

What is evaluation order of function parameters in C?

It is compiler dependent in C. It is never safe to depend on the order of evaluation of side effects. For example, a function call like below may very well behave differently from one compiler to another: void func (int, int); int i = 2; func (i++, i++); There is no guarantee (in either the C or the C++ standard language definitions) that the incre

1 min read

Can We Use Function on Left Side of an Expression in C and C++?

In C, it is not possible to have function names on the left side of an expression, but it's possible in C++. How can we use the function on the left side of an expression in C++? In C++, only the functions which return some reference variables can be used on the left side of an expression. The reference works in a similar way to pointers, so whenev

1 min read

Default Arguments and Virtual Function in C++

Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument. Virtual function is a member function that is declared within a base class and is redefined(Overr

3 min read

How to Return a Local Array From a C++ Function?

Here, we will build a C++ program to return a local array from a function. And will come across the right way of returning an array from a function using 3 approaches i.e. Using Dynamically Allocated ArrayUsing Static Array Using Struct C/C++ Code // C++ Program to Return a Local // Array from a function While // violating some rules #include &lt;i

3 min read

C++ | Function Overloading and Default Arguments | Question 5

Which of the following in Object Oriented Programming is supported by Function overloading and default arguments features of C++. (A) Inheritance (B) Polymorphism (C) Encapsulation (D) None of the above Answer: (B) Explanation: Both of the features allow one function name to work for different parameter. Quiz of this Question

1 min read

C++ | Function Overloading and Default Arguments | Question 2

Output? #include&lt;iostream&gt; using namespace std; int fun(int x = 0, int y = 0, int z) { return (x + y + z); } int main() { cout &lt;&lt; fun(10); return 0; } (A) 10 (B) 0 (C) 20 (D) Compiler Error Answer: (D) Explanation: All default arguments must be the rightmost arguments. The following program works fine and produces 10 as output. #include

1 min read

C++ | Function Overloading and Default Arguments | Question 3

Which of the following overloaded functions are NOT allowed in C++? 1) Function declarations that differ only in the return type int fun(int x, int y); void fun(int x, int y); 2) Functions that differ only by static keyword in return type int fun(int x, int y); static int fun(int x, int y); 3)Parameter declarations that differ only in a pointer * v

1 min read

C++ | Function Overloading and Default Arguments | Question 4

Predict the output of following C++ program. include&lt;iostream&gt; using namespace std; class Test { protected: int x; public: Test (int i):x(i) { } void fun() const { cout &lt;&lt; &quot;fun() const &quot; &lt;&lt; endl; } void fun() { cout &lt;&lt; &quot;fun() &quot; &lt;&lt; endl; } }; int main() { Test t1 (10); const Test t2 (20); t1.fun(); t

1 min read

C++ | Function Overloading and Default Arguments | Question 5

Output of following program? #include &lt;iostream&gt; using namespace std; int fun(int=0, int = 0); int main() { cout &lt;&lt; fun(5); return 0; } int fun(int x, int y) { return (x+y); } (A) Compiler Error (B) 5 (C) 0 (D) 10 Answer: (B) Explanation: The statement "int fun(int=0, int=0)" is declaration of a function that takes two arguments with de

1 min read

Virtual Function in C++

A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth

6 min read

wcscpy() function in C++ with Examples

The wcscpy() function is defined in cwchar.h header file. The wcscpy() function is used to copy a wide character string from source to destination. Syntax: wchar_t *wcscpy(wchar_t *dest, const wchar_t *src); Parameters: This method accepts the following two parameters: dest: specifies the pointer to the destination array. src: specifies the pointer

1 min read

wcscmp() function in C++ with Examples

The wcscmp() function is defined in cwchar.h header file. The wcscmp() function is used to compares two null terminating wide string and this comparison is done lexicographically. Syntax: int wcscmp(const wchar_t* str1, const wchar_t* str2); Parameters: This method takes the following two parameters: str1: This represents the pointer to the first s

2 min read

strtoul() function in C/C++

The strtoul() function in C/C++ which converts the initial part of the string in str to an unsigned long int value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. This function discard any white space characters until the first non-whitespace character is found, then takes as many characters as poss

3 min read

wcscspn() function in C/C++

The wcscspn() function in C/C++ searches the first occurrence of a wide character of string_2 in the given wide string_1. It returns the number of wide characters before the first occurrence of that wide character . The search includes the terminating null wide characters. Therefore, the function will return the length of string_1 if none of the ch

2 min read

asctime() function in C++

The asctime() function is defined in the ctime header file. The asctime() function converts the given calendar time of structure tm to a character representation i.e human readable form. Syntax: char* asctime(const struct tm * time_ptr); Parameter: This function accepts single parameter time_ptr i.e pointer to the tm object to be converted. Return

1 min read

C Library Function - difftime()

The difftime() is a C Library function that returns the difference in time, in seconds(i.e. ending time - starting time). It takes two parameters of type time_t and computes the time difference in seconds. The difftime() function is defined inside the &lt;time.h&gt; header file. Syntax The syntax of difftime() function is as follows: double difftim

1 min read

Measure execution time of a function in C++

We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11. We have discussed at How to measure time taken by a program in C. The functions described there are supported in C++ too but they are C specific. For clean and robust C++ programs we should strive to use C++ specific language constr

3 min read

Count the number of objects using Static member function

Prerequisite : Static variables , Static Functions Write a program to design a class having static member function named showcount() which has the property of displaying the number of objects created of the class. Explanation: In this program we are simply explaining the approach of static member function. We can define class members and member fun

2 min read

Practice Tags :

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy

rename function in C - GeeksforGeeks (6)

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('

'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `

${comment_text}

`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `

${suggest_val}

`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `

Thank You!

Your suggestions are valuable to us.

You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.

`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('

'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('

'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });

rename function in C - GeeksforGeeks (2024)
Top Articles
Paintball Frequently Asked Questions
Marathon Preparation: 9 things to do before your race
Fort Morgan Hometown Takeover Map
Victory Road Radical Red
Gomoviesmalayalam
Fredatmcd.read.inkling.com
Arrests reported by Yuba County Sheriff
CHESAPEAKE WV :: Topix, Craigslist Replacement
Category: Star Wars: Galaxy of Heroes | EA Forums
Concacaf Wiki
Wmlink/Sspr
Cvs Devoted Catalog
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Savage X Fenty Wiki
[2024] How to watch Sound of Freedom on Hulu
Zendaya Boob Job
Aspen.sprout Forum
Hoe kom ik bij mijn medische gegevens van de huisarts? - HKN Huisartsen
Les Schwab Product Code Lookup
Best Nail Salon Rome Ga
Kitty Piggy Ssbbw
Ostateillustrated Com Message Boards
Hewn New Bedford
Katie Sigmond Hot Pics
Conan Exiles Sorcery Guide – How To Learn, Cast & Unlock Spells
College Basketball Picks: NCAAB Picks Against The Spread | Pickswise
Garnish For Shrimp Taco Nyt
2021 Volleyball Roster
Zillow Group Stock Price | ZG Stock Quote, News, and History | Markets Insider
Www Va Lottery Com Result
Gotcha Rva 2022
8000 Cranberry Springs Drive Suite 2M600
Koninklijk Theater Tuschinski
Piri Leaked
Move Relearner Infinite Fusion
Divide Fusion Stretch Hoodie Daunenjacke für Herren | oliv
Filmy Met
Issue Monday, September 23, 2024
Craigs List Tallahassee
Why Are The French So Google Feud Answers
Emily Katherine Correro
47 Orchid Varieties: Different Types of Orchids (With Pictures)
State Legislatures Icivics Answer Key
Compare Plans and Pricing - MEGA
Shane Gillis’s Fall and Rise
Vons Credit Union Routing Number
Costco Gas Foster City
Cleveland Save 25% - Lighthouse Immersive Studios | Buy Tickets
Gabrielle Abbate Obituary
Christie Ileto Wedding
Plasma Donation Greensburg Pa
Latest Posts
Article information

Author: Ms. Lucile Johns

Last Updated:

Views: 6230

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Ms. Lucile Johns

Birthday: 1999-11-16

Address: Suite 237 56046 Walsh Coves, West Enid, VT 46557

Phone: +59115435987187

Job: Education Supervisor

Hobby: Genealogy, Stone skipping, Skydiving, Nordic skating, Couponing, Coloring, Gardening

Introduction: My name is Ms. Lucile Johns, I am a successful, friendly, friendly, homely, adventurous, handsome, delightful person who loves writing and wants to share my knowledge and understanding with you.