Question

Problems Updating fopen() to fopen_s() in C++

Asked by: dleehanson

I recently got charged with updating / modifying an existing C++ DLL.  I starting updating some of the functions to their security-friendly counterparts and am running into problems.

It seems that I am having problems with my change of fopen() to fopen_s().  For some reason the files aren't closing anymore, since I can't open them in windows.  I get an access violation saying another program is still accessing it.

So my question is: What all do I need to do to update to fopen_s()?

<snip>

//if( (plltCreateFile = fopen(fqnCreate,"w")) == NULL)  //Old code
if( (fopen_s(&plltCreateFile, fqnCreate,"w")) == NULL)
{
      returnValue = (-1);
}
else
{
      // New stuff
      sprintf_s(fqnLine,"%sIn\\line%d.dat",Zebra.shareName,LineNumber);
      fprintf(plltCreateFile,"%s\n",PalletCreate(fqnLine,palletCode,timeBuffer));

      fclose(plltCreateFile);
      plltCreateFile = NULL;
}

I don't have a great deal of experience with C++, so any help is greatly appreciated.

--Charly

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-10-24 at 13:46:58ID22915886
Tags

fopen_s

Topic

C++ Programming Language

Participating Experts
5
Points
350
Comments
33

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. fopen in unix.
    I have a subroutine that opens a file, then calls another routine to do some work on the file, and finally closes the file. The first time I call this routine it works fine, but subsequent calls fail with errno saying "Not a directory". It is trying to open the sam...
  2. fprintf
    Following is the code:#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <iostream.h> #include <time.h> #define NOQUOTE 0 #define FIRSTQUOTE 1 #define SECNDQUOTE 2 void...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: peetmPosted on 2007-10-24 at 14:04:41ID: 20142900

The docs for fopen_s say that the function returns 0 for success.  As NULL is most often #defined as 0 surely your code shows that the function fails if it actually works!?

So, your fclose() call is in the wrong branch - and doesn't get called in other words??

 

by: peetmPosted on 2007-10-24 at 14:07:47ID: 20142923

Your code should be something like more like this:

errno_t result = fopen_s(&plltCreateFile, fqnCreate,"w"));

if(result != 0)
{
      ...
}
else
{
    ....

    fclose(pltCreateFile);
}

 

by: jkrPosted on 2007-10-24 at 14:10:58ID: 20142933

Are you checking the return value of 'fclose()'? I.e.

      if ( fclose( plltCreateFile) )
      {
         printf( "Error closing file\n" );
      }

 

by: evilrixPosted on 2007-10-24 at 14:26:51ID: 20143037

You are converting code that is using POSIX compliant functions to Microsoft's "secure" versions. Question -- why? What is your rational? Because Microsoft said so? If you ever need to port this code it'll be a can of worms you'll have to open all over again! Besides, I wonder, are these functions really anymore secure than their Posix counterparts?

If you are prepared to go down this route I'd just bite the bullet and convert the code base to use STL streams. You'll get all the flexibility of streams with all the portability of STL (did I really say that?).

Your example rewritten is something like this...

#include <fstream>
#include <sstream>

int main() // Exception handling omitted for clarity
{
      int retval = -1;

      std::ofstream fs("myfile.txt");
      
      if(fs.is_open())
      {
            std::stringstream ssLine;

            ssLine
                  << Zebra.shareName
                  << "In\\"
                  << LineNumber
                  << ".dat";

            fs
                  << PalletCreate(ssLine.str().c_str(),palletCode,timeBuffer)
                  << std::endl;

            retval = fs.good() ? 0 : -1;
      }

      return retval;
}

 

by: itsmeandnobodyelsePosted on 2007-10-24 at 23:37:36ID: 20145495

>>>> You are converting code that is using POSIX compliant
>>>> functions to Microsoft's "secure" versions.

There is nothing wrong with that as long as you accept that it is not portable. The _s functions check input parameters and throw exceptions if for example you are passing a NULL pointer.

>>>> if( (fopen_s(&plltCreateFile, fqnCreate,"w")) == NULL)
The problem is that fopen_s returns errno_t (and not FILE pointer). So, the fopen_s returns 0 for success and the code in the else branch never was called. See http://msdn2.microsoft.com/en-us/library/z5hh6ee9(VS.80).aspx for more information.

Regards, Alex

 

by: evilrixPosted on 2007-10-24 at 23:55:34ID: 20145558

I didn't say it was wrong -- I was pointing out  possibles issue of portability and offering and alternative for consideration.

 

by: itsmeandnobodyelsePosted on 2007-10-25 at 05:39:55ID: 20147003

>>>> I didn't say it was wrong

You said:

- Because Microsoft said so?
- it'll be a can of worms you'll have to open all over again!
- I wonder, are these functions really anymore secure than
  their Posix counterparts?

I would interpret your statements as a non-recommendation and calling that 'pointing out  possibles issue of portability' surely is a euphemism. Are you a politician?

MS made a lot of bad attempts to prevent developers from making portable code. The _s functions maybe is one of these attempts but the idea to have more secure wrappers for some old and unsafe runtime functions is good and you easily could add these function wrappers to any other system/platform if needed for portability without 'opening a can of worms'.

 

 

by: evilrixPosted on 2007-10-25 at 06:02:22ID: 20147176

...or you could use STL streams as a viable, cross-platform, alternative, no?

Incidentally, not once did I use the word "wrong" in my post! I was just questioning the rational behind these changes to ensure they are really necessary; which, doesn't mean I am stating they are wrong.

 

by: dleehansonPosted on 2007-10-25 at 09:42:14ID: 20149055

Actually, I don't have much experience with C++ at all, so all I did was do a bit of google research on the warnings the compiler was giving me.  That's pretty much the whole rationale for it.  I just don't want to leave a legacy of crappy code behind for the next guy.  So if it isn't necessary to update it I would actually prefer to leave it as is.

Are there any significant risks in not updating it?  The DLL in question is just a small, couple 100 line program which I need to invoke Windows system calls (print, file I/O) from a PLC controller (Programmable Logic Computer, used in the automation industry).

Thanks again for the advice guys.

--Charly

 

by: jkrPosted on 2007-10-25 at 09:45:08ID: 20149076

Again: Are you checking the return value of 'fclose()'? I.e.

      if ( fclose( plltCreateFile) )
      {
         printf( "Error closing file\n" );
      }
back to top

 

by: evilrixPosted on 2007-10-25 at 10:00:08ID: 20149187

dleehanson: -

Based upon your rational, it is my opinion that these changes are unnecessary. Providing Posix compliant functions are used correctly, they are just as safe as Microsoft's "secure" versions. If the code already works without problem and there is no other compelling reason than to do so I wouldn't change it. The more you change the more you break!

You can disable the warnings very simply by defining the following macro as a compile time parameter to the compiler: _CRT_SECURE_NO_WARNINGS (set this in the project settings). Alternatively, if you just want to disbale the warnings specifically at source you can just use a #pragma warning block around the offending lines.

More info can be found here...

http://msdn2.microsoft.com/en-us/library/8ef0s5kh(VS.80).aspx

I hope this helps.

Good luck :)

 

by: dleehansonPosted on 2007-10-25 at 10:08:33ID: 20149267

No, it doesn't look like the previous developer did that.  Here is all I think he does:

if( (plltCreateFile = fopen(fqnCreate,"w")) == NULL)
{
      returnValue = (-1);

}//PLLTCREAT dat can't be created
else
{
      // New stuff
      sprintf(fqnLine,"%sIn\\line%d.dat",Zebra.shareName,LineNumber);
      fprintf(plltCreateFile,"%s\n",PalletCreate(fqnLine,palletCode,timeBuffer));

      fclose(plltCreateFile);
      plltCreateFile = NULL;

}//PLLTCREAT dat file can be created

If the code is running as a DLL, there isn't a console to print to, correct?  So what would happen if I put that code in there?  A console pops up?  It gets ignored?  Throws an exception?

Thanks for the continued help.

--Charly

 

by: Infinity08Posted on 2007-10-25 at 10:09:24ID: 20149275

Or in short : if it isn't broken, don't fix it ;)

 

by: jkrPosted on 2007-10-25 at 10:12:06ID: 20149302

>>So what would happen if I put that code in there?  A console pops up?

Actually, nothing will happen. You can also make that

      if ( fclose( plltCreateFile) )
      {
         MessageBox( NULL, "Error closing file\n", fqnCreate, MB_OK );
      }

to receive a message box in the case of an error.

 

by: itsmeandnobodyelsePosted on 2007-10-25 at 10:12:32ID: 20149305

>>>> Are there any significant risks in not updating it?

No. There are no risks in updating it to fopen_s and to not updating it.


>>>> What all do I need to do to update to fopen_s()?

You have to change the if statement to

errno_t ret = 0;
if( (ret = fopen_s(&plltCreateFile, fqnCreate,"w")) != 0)   // NOTE, ret == 0 is SUCCESS
{
        returnValue = ret;   // we got an error
}
else
{
     ...
}

Regards, Alex

 

by: itsmeandnobodyelsePosted on 2007-10-25 at 10:19:42ID: 20149374

>>>> so all I did was do a bit of google research on the
>>>> warnings the compiler was giving me.  

If the warnings only is because of fopen you can ignore it. If you have other warnings you may post them here.

 

by: evilrixPosted on 2007-10-25 at 10:27:18ID: 20149428

The Posix functions (like any tool) are safe when used safely. If I was cynical I might think the idea is to 'scare' you into changing/writing the code to use their [Microsoft] functions just to tie you in to their compiler and hence their platform. Ho hum.

 

by: itsmeandnobodyelsePosted on 2007-10-25 at 10:27:52ID: 20149437

>>>> You can disable the warnings very simply by defining the following macro

Actually, you got some funny advice here.

At the one hand you should not change old code (though it is only a change from == to !=) and at the other hand you should add code to suppress warnings.

If there is any unnecessary change then code to suppress warnings is the most unnecessary one.

 

by: itsmeandnobodyelsePosted on 2007-10-25 at 10:33:50ID: 20149489

>>>> The Posix functions (like any tool) are safe when used safely.
Yes, and the sky is blue and the meadow is green.

evilrix, the fopen_s wasn't the problem but only the wrong interpretation of the return value. And it won't be an issue even if you will post another 100 comments with wild attacks against MS.

 

by: evilrixPosted on 2007-10-25 at 10:35:00ID: 20149500

Ok, I don't want to get into needless debate about this, but...

(a) I wasn't advocating... I was providing information, how it is used is up to the reader.
(b) It's not a code change, it's a simple project setting, hence I stated "(set this in the project settings)".
(c) The MSDN page I provided gives details of how to do this and what is involved!

If he's happy with the warnings fine, if he's not and would like to suppress them this will do it!

 

by: evilrixPosted on 2007-10-25 at 10:37:23ID: 20149518

>> the fopen_s wasn't the problem but only the wrong interpretation of the return value

Fine, but this doesn't change the fact the changes are unnecessary!

BTW: I am not "attacking" MS, I am just stating there is no real good reason for these functions!

 

by: evilrixPosted on 2007-10-25 at 10:38:51ID: 20149534

Typo -- Fine, but this doesn't change the fact the changes ARE NOT unnecessary!

 

by: dleehansonPosted on 2007-10-25 at 10:40:00ID: 20149545

All I added was code to suppress the one type of warning
#pragma warning(disable : 4996):

Are there any other further ranging effects to doing this?  If anything it just makes things easier to debug, since I don't get a horde of warnings all the time.

I'm also getting this warning:
            warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification

Can I supress this too, or is there an important problem to address here?

Thanks everyone.

--Charly

 

by: evilrixPosted on 2007-10-25 at 10:41:15ID: 20149552

Arrrgg... it's still wrong.

Oh hell, you know what I mean -- I can't type tonight :)

Anyway, I think this question is done.

 

by: jkrPosted on 2007-10-25 at 10:43:09ID: 20149570

>>Are there any other further ranging effects to doing this?

Usually not. The old code will compile.

>> warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO'
>>specification

You can safely ignore that one. '/EDITANDCONTINUE' means that you can change the code during debugging (which in some cases can be useful) and that this is being disabled.

 

by: jkrPosted on 2007-10-25 at 10:44:09ID: 20149580

BTW, it would be interesting to know what is going wrong anyway - since the main difference between the two functions is extended parameter validation, chances are that you end up with the same problem again.

 

by: evilrixPosted on 2007-10-25 at 10:45:06ID: 20149592

I would add the project macro I stated above as it will be global (and doesn't change any code). The only effect of this setting is to suppress warnings about "insecure" functions!

The other warning is because you have edit and continue enabled with incremental linking disabled. Just disable the former or enable the latter; but make sure you know what both these settings do before you decide which to change!

 

by: dleehansonPosted on 2007-10-25 at 11:00:12ID: 20149726

jkr,

There isn't anything wrong when I run the original code.  I don't get any files hanging open etc.  The problems arose when I was making changes, which I plan on not doing now.

evilrix,

I think I know what edit and continue means, but not what incremental linking is.  All I do is compile my project and copy it into my PLC test program, so I don't really need any fancy debugging features in VS.

--Charly

 

by: itsmeandnobodyelsePosted on 2007-10-25 at 11:03:04ID: 20149758

>>>> warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/INCREMENTAL:NO' specification
>>>> Can I supress this too, or is there an important problem to address here?

It is a linker warning that only happens in debug mode. Your debugger was able to 'compile on the fly' while debugging, but the option was discarded because of project settings. Actually it is a MS bug and has *no* importance. You can safely ignore it.


 

by: itsmeandnobodyelsePosted on 2007-10-25 at 11:06:50ID: 20149786

>>>> BTW, it would be interesting to know what is going wrong anyway

jkr, peetm actually detected the error in the very first comment of that thread:

while fopen returns NULL if the open fails, fopen_s returns 0 if the open succeeds. So, the fclose was never reached on success.

Regards, Alex

 

by: evilrixPosted on 2007-10-25 at 11:07:24ID: 20149791

Incremental Linking -- in detail...
http://www.airs.com/blog/archives/55

 

by: dleehansonPosted on 2007-10-25 at 11:42:24ID: 20150121

Ok, I think I have gotten all of my questions answered on this topic.  Here's how I am going to do the points:

125 to peetm for answering my initial question
75 to evilrix, itsmeandnobodyelse, and jkr for helping with all the subsequent questions.

I hope this seems fair to everyone as I greatly appreciate everyone's help.

--Charly

 

by: evilrixPosted on 2007-10-25 at 11:50:22ID: 20150188

Sure, fine by me  :)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...