Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Harold Ramis Drugs posted:

Ok, thanks. I think this works, I'm also pretty sure that I'm managing the memory correctly.

http://pastebin.com/BJwrkTGt

Is there any way I can make this program more modular though? As you can see, I'm basically using the same ~40 lines of code 4 times, and I think I could probably move that to a method that calls in a string and an int.

A couple things, in addition to what Suspicious Dish said about extracting your code into functions.

The first is that you're making the assumption (very common in new C programmers) that everything you put in a pointer variable has to be malloc'ed. That's not true; you can use a local array anywhere that you'd use a pointer:
code:
char one[1];
...
scanf("%s", one);
And a local variable works exactly like an array of capacity one, so the above could even be:
code:
char one;
...
scanf("%s", &one);
The second is that a C string always ends with a '\0' character, so if you want to be able to store an n-byte string, you need a buffer of size at least n+1. That's true whether you're malloc'ing it or using a local array, like we did in the first point. So going back to what I just wrote, the first example should really be char one[2];, and the second example just can't be made to work (with the %s specifier; there is a %c specifier to read a single character, though).

The third is that using scanf to read a string into a fixed-size buffer is inherently dangerous, because when scanf sees %s in its format string, it'll just keep copying characters over until it sees the next whitespace character. You can make this safe by specifying a maximum size in the format specifier, e.g. "%20s". Remember that we need space for that '\0' character, so the number you give here needs to be one less than the allocated size of the buffer; that is, if you have an array of 10 chars, you can safely read into it with "%9s".

The fourth is just that you can read multiple values using scanf at once: you can just say scanf("%s %d", two, &third);.

rjmccall fucked around with this message at 06:00 on May 7, 2012

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Since it's late at night and I really don't want to go poking through the C specification, I have a simple question, actually: do stack-based variables get deallocated when you leave scope, or are they all cleaned up at the end of the function? That is, will this work properly?

code:
static void
foo(int c)
{
  int *a;
  if (c > 50) {
    int b = 20;
    a = &b;
  } else {
    int b = 25;
    a = &b;
  }

  printf("%d\n", *a);
}
EDIT: for a good explanation of stack vs. heap allocation, I really recommend Eric Lippert's series. Both parts are geared towards C#, but the second explains the motivation for pretty much all languages that make the distinction. Ignore the parts about automatic garbage collection, in C, you do garbage collection explicitly with free, and the mark and sweep stuff don't apply.

Suspicious Dish fucked around with this message at 06:22 on May 7, 2012

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
When they leave scope, but that specific example is likely to work by coincidence.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Suspicious Dish posted:

Since it's late at night and I really don't want to go poking through the C specification, I have a simple question, actually: do stack-based variables get deallocated when you leave scope, or are they all cleaned up at the end of the function? That is, will this work properly?

quote:

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined.

quote:

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way

So the example you posted is hitting UB when you do a read through a.

Note that your example is likely to work in practice, but making some changes to that function could easily break it. (e.g. adding a variable that's only accessed after the entire scope of b)

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Is Accelerated C++ a good choice of book for a Python and Java amateur who wants to learn C++ to write some Windows applications, or is there something more tailored for Windows?

MutantBlue
Jun 8, 2001

Thermopyle posted:

Is Accelerated C++ a good choice of book for a Python and Java amateur who wants to learn C++ to write some Windows applications, or is there something more tailored for Windows?

Accelerated C++ is a great book but it only covers the C++ language and standard library. There is nothing about Windows or any other OS specific APIs.

Poniard
Apr 3, 2011



So I'm trying to fill a struct from an input file. The input file is a chart with 480 lines and 11 items in each. Conveniently, the items are separated by commas if it's opened in a text editor.

This is the struct I'm trying to use:
code:
struct ADC{
	char PartID[20];	
	char Resolution[20]; 
	char ThruPutRate[20]; 
	char FullPwrBW[20];
	char NumChan[20];
	char AinRange[20]; 
	char SupplyV[20];	
	char PwrDiss[20];	
	char OpTempRange[20]; 
	char PkgType[20]; 
	char Price[20];
};
I could malloc for each part of it, but I figured this would be easier.
Streaming characters into one part, then stopping when it hits a comma and putting an end of string character there seems to work for me, but trying to print any part of the struct returns a blank space.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Thermopyle posted:

Is Accelerated C++ a good choice of book for a Python and Java amateur who wants to learn C++ to write some Windows applications, or is there something more tailored for Windows?
For dealing with Windows stuff there's really not very much C++ you'd need to know at all; it's all about the API, which is C anyway (and you still don't really need to know much C, the API documentation tells you everything) - unless you're going to be using some middleware library, in which case the documentation of that library is what you'd be dealing with.

If your project is more new functionality and less Windows interface then the C++ book would probably be good anyway. In my experience, the best thing for learning the Windows API is the ancient Win32SDK.hlp file, but nowadays it's tough to even read .hlp files. :(

The modern compiled html version just doesn't have the same intuitive structure to it.

Dicky B
Mar 23, 2004

Thermopyle posted:

Is Accelerated C++ a good choice of book for a Python and Java amateur who wants to learn C++ to write some Windows applications, or is there something more tailored for Windows?
If you are going the win32/COM route, C++ in Action and the companion tutorial give a pretty concise overview of both the language and the win32 API.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

roomforthetuna posted:

C stuff


Dicky B posted:

C++ stuff

Hmm, well...

Let me put it this way. Short-term I'm wanting to write a console application that just sits there receiving Device Events and writes them to stdout.

On that MSDN page they give a sample implementation in C++, but I don't have any idea how to get from that to a running console app. Maybe it would be easier implemented in C...I don't have a clue.

Thermopyle fucked around with this message at 20:51 on May 7, 2012

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Thermopyle posted:

Hmm, well...

Let me put it this way. Short-term I'm wanting to write a console application that just sits there receiving Device Events and writes them to stdout.

On that MSDN page they give a sample implementation in C++, but I don't have any idea how to get from that to a running console app. Maybe it would be easier implemented in C...I don't have a clue.
Can you be more specific about where the sample implementation in C++ is? I don't see it on that page. I'd be rather surprised if it's really in C++ since all the functions discussed on that page appear to be C functions.

Getting a thing running as a console app is really not a function of C or C++ so much as a function of your development environment and linker. For a Windowed app you start with WinMain(...), for a console app you start with main(...), and then you configure some settings so that it doesn't complain that the one the linker expected isn't there.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

roomforthetuna posted:

Can you be more specific about where the sample implementation in C++ is? I don't see it on that page. I'd be rather surprised if it's really in C++ since all the functions discussed on that page appear to be C functions.

Getting a thing running as a console app is really not a function of C or C++ so much as a function of your development environment and linker. For a Windowed app you start with WinMain(...), for a console app you start with main(...), and then you configure some settings so that it doesn't complain that the one the linker expected isn't there.

poo poo, wrong link. Here it is: http://msdn.microsoft.com/en-us/library/windows/desktop/dd370810(v=vs.85).aspx

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Thermopyle posted:

poo poo, wrong link. Here it is: http://msdn.microsoft.com/en-us/library/windows/desktop/dd370810(v=vs.85).aspx
Ah, it's COM stuff, yeah, that'll be C++. You'd probably want Dicky B's recommendations then, because COM is a crazy confusing mess if not introduced properly (and not much better even after you understand it).

That example is pretty opaque and doesn't show how you'd use the class, which is pretty typical of COM example code unfortunately.

raminasi
Jan 25, 2005

a last drink with no ice
I don't know what your eventual target is for this, but if you can avoid COM/C++ then you probably want to at least consider it. For example, you can wrap the API calls and interact with them using C#.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

GrumpyDoctor posted:

I don't know what your eventual target is for this, but if you can avoid COM/C++ then you probably want to at least consider it. For example, you can wrap the API calls and interact with them using C#.

Oh thanks for that! I think I'd much rather use C#.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.
Ok.

I have some parasoft unit tests that look like they were autogenerated.

I want to move them to MSTEST's unit testing solution in VS11 for unimportant reasons.

The conversion is straightforward, except in the case where parasoft is unit testing destructor methods.

See:
code:
 TEST_METHOD(x7eCBoundingBox_1)
{
    /* Testing destructor - begin new scope. */
    {
    /* Pre-condition initialization */
    /* Initializing argument 0 (this) */ 
        /* Initializing constructor argument 1 (pt1) */ 
            /* Initializing constructor argument 1 (unknown) */ 
            double _arg1_1  = DBL_MAX;
            /* Initializing constructor argument 2 (unknown) */ 
            double _arg2_1  = DBL_MAX;
            /* Initializing constructor argument 3 (unknown) */ 
            double _arg3_1  = DBL_MAX;
        ::Math::CPoint3d _pt1_0 (_arg1_1, _arg2_1, _arg3_1);
        /* Initializing constructor argument 2 (pt2) */ 
            /* Initializing constructor argument 1 (unknown) */ 
            double _arg1_2  = DBL_MAX;
            /* Initializing constructor argument 2 (unknown) */ 
            double _arg2_2  = DBL_MAX;
            /* Initializing constructor argument 3 (unknown) */ 
            double _arg3_2  = DBL_MAX;
        ::Math::CPoint3d _pt2_0 (_arg1_2, _arg2_2, _arg3_2);
    ::Math::CBoundingBox TestObject (_pt1_0, _pt2_0);
    /* Object destruction at the end of scope */
    }
    /* Post-condition check */
}
This obviously is going to be useless if I move it over to MSTEST without checking something. I can only infer parasoft is doing some kind of checking/code analysis to make the destructor works right.

If I wanted to unit test a destructor in C++ using mstest, what would I do?

My inclination is to just comment this all out and be like "whatever." That is a possibility. But if I wanted to do this the 'right' way, what would I do?

raminasi
Jan 25, 2005

a last drink with no ice

Thermopyle posted:

Oh thanks for that! I think I'd much rather use C#.

Probably. While opinions on C++ in general vary, COM is pretty much universally hated. If you have any questions setting up the Platform/Invoke wrappers you can ask them over in the .Net megathread.

Kudaros
Jun 23, 2006
Im doing a simulation where I've declared a struct with, at the moment, three spatial coordinates (double x,y,z). Ill go through them and define the positions. The problem is, I potentially need 75 million or more points. I was using an array with a very, very coarse mesh. I was declaring pnts[N] where N is, say 1000 in the beginning.

Is it possible to use malloc (or any other recommendation?) for such spaces? The struct will eventually have, I think, 5 variables inside it.

As a hypothetical, say pnt[N] is a data type defined by a struct with 10 variables - how demanding does this become in terms of memory?

edit: ok babby's first memory allocation - Ive successfully answered my own question by experimenting with sizeof(stuff) and reading.

but still: Anyone have any idea about the practical limit of struct variables - at which point Ill have to beg or pay for supercomputer time?

Sorry for reinforcing stereotypes about physics people and programming.

Kudaros fucked around with this message at 17:32 on May 9, 2012

shrughes
Oct 11, 2008

(call/cc call/cc)

Kudaros posted:

but still: Anyone have any idea about the practical limit of struct variables - at which point Ill have to beg or pay for supercomputer time?

You mean the practical limit for array sizes?

The practical limit is how much memory you have on your computer, divided by how many arrays you have at a time, I suppose, with some allowances possibly made for heap fragmentation. (If somebody calls x=malloc(1000), y=malloc(1000), z=malloc(1000), free(y), y=malloc(2000), you're probably going to have an unused block of 1000-ish bytes somewhere in there. Imagine this with array sizes 1 million times as large.)

So let's say that the practical limit on the right laptop is 32 billion and on a desktop is, say, 64 billion, but really it can be higher for desktops or "servers" without going to a "supercomputer".

Jinx
Sep 9, 2001

Violence and Bloodshed

Kudaros posted:

Im doing a simulation where I've declared a struct with, at the moment, three spatial coordinates (double x,y,z). Ill go through them and define the positions. The problem is, I potentially need 75 million or more points. I was using an array with a very, very coarse mesh. I was declaring pnts[N] where N is, say 1000 in the beginning.

Is it possible to use malloc (or any other recommendation?) for such spaces? The struct will eventually have, I think, 5 variables inside it.

As a hypothetical, say pnt[N] is a data type defined by a struct with 10 variables - how demanding does this become in terms of memory?

edit: ok babby's first memory allocation - Ive successfully answered my own question by experimenting with sizeof(stuff) and reading.

but still: Anyone have any idea about the practical limit of struct variables - at which point Ill have to beg or pay for supercomputer time?

Sorry for reinforcing stereotypes about physics people and programming.
Generally there is an upper limit on the number of data members of a class/struct (16384 for C++), but I think you are actually asking about allocating memory for N number of structs.

Do you know the difference between stack and heap memory? Basically defining an array like this: char myFirstArray[100]; allocates a block of 100 bytes* on the stack. Now the important thing to note here is that stack size is (very) limited (the actual size is implementation dependent, but default on Linux is 10240KB, or 10MB).

So let's say you have a struct with 10 doubles - let's assume each double is 8 bytes, so that's 80 bytes per struct. If you want to be able to store 75 million of these structs simultaneously you will need 80 * 75000000 = 6000000000 bytes (or ~5.6GB) of memory.

Furthermore malloc has a limit on the size of a single allocation: SIZE_MAX (or the largest possible value that can be stored in a size_t type).

*I am of course ignored alignment issues (http://en.wikipedia.org/wiki/Data_structure_alignment).

Kudaros
Jun 23, 2006
That's quite educational, thanks. This simulation is (physically) very simplistic at the moment and already starting to get taxing.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
One option for your giant structure that's bigger than the memory available is to look into memory-mapped files. You'd have to be mapping and unmapping blocks of it as you roll along, so you'd be wanting to keep your access as consecutive as possible (because otherwise it would be horrendously slow), but it does give you more flexibility on how much stuff you can be working with (at a nominal cost of both complexity and speed).

Edit: and if you're on a 64-bit machine then you wouldn't need to remap the view of the file, you could just treat it as one big contiguous block of slow memory, if the mmap functions have 64-bit versions.

roomforthetuna fucked around with this message at 22:05 on May 9, 2012

Backno
Dec 1, 2007

Goff Boyz iz da rudest Boyz

SKA SUCKS
So I have a question for you guys. I am going back to school for engineering in the fall. One of the classes that I will be taking in the first year is " Introduction to Programming Concepts" with the following description:

quote:

Basic concepts and applications of software programming for solving engineering problems. Topics include techniques for developing structured algorithms, data input and output, conditional statements, loops, recursion, functions, arrays and elementary concepts in mathematical programming. Examples, homework, and applications of programming concepts make extensive use of the C programming language.


I have seen some mentions of the MIT OpenCourseWare Class. The class looks interesting, is free, and teaches the basics of programming concepts. What I am worried about is will learning how to program in Python make learning C harder or give me some bad habits. Would I be better off just getting one of the C books mentioned in this thread and trying to learn from that?

I know these questions might be stupid, but I know absolutely NOTHING about programming and am afraid that I will get left behind/fail if I don't take the time to get my head wrapped around the problem.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
An introductory programming course will teach you a little of two different things: first, how to program, and second, how to use some specific language.

Talking about the former, learning a bit of how to program in one course will help you to learn a bit more in another. (It'll also help protect you if your teacher isn't that good.)

Talking about the latter, learning to use Python will definitely help you to learn to use C, not because the languages are all that similar (although they have a lot in common), but because C can be very daunting if you're simultaneously learning it *and* learning how to program at all. Anything that helps you understand computers more will help you to learn C.

You should not obsess about learning bad habits. Understand that you will come out of your first programming experiences with some bad habits. Keep an open mind and learn from your mistakes.

Doctor Malaver
May 23, 2007

Ce qui s'est passé t'a rendu plus fort
I have a program made in C that a friend made ages ago to rank and pair up teams of players (for our old Warcraft II league, but can be used for anything). It uses text files and works in DOS prompt. The .exe doesn't work any more on my 64-bit Windows. I still have the .c file. Can someone compile it to run on 64-bit Windows? I don't know how much work this is.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!
Is there a library out there that provides malloc/realloc/free facilities using an existing flat memory buffer? Preferably one that isn't GPL?

Paolomania
Apr 26, 2006

Doctor Malaver posted:

I have a program made in C that a friend made ages ago to rank and pair up teams of players (for our old Warcraft II league, but can be used for anything). It uses text files and works in DOS prompt. The .exe doesn't work any more on my 64-bit Windows. I still have the .c file. Can someone compile it to run on 64-bit Windows? I don't know how much work this is.

It should not be too difficult. You can download everything you need for free. I would be glad to walk you through it. First step: post the .c file to pastebin.com so we can take a look at it and see how outdated its dependencies are. So long as its not using MS-DOS interrupts for I/O you should be fine.

Doctor Malaver
May 23, 2007

Ce qui s'est passé t'a rendu plus fort

Paolomania posted:

It should not be too difficult. You can download everything you need for free. I would be glad to walk you through it. First step: post the .c file to pastebin.com so we can take a look at it and see how outdated its dependencies are. So long as its not using MS-DOS interrupts for I/O you should be fine.

OK, let's try!
http://pastebin.com/zFAVnBfD

Colonel Taint
Mar 14, 2004


Was pretty easy to get it to compile. I couldn't say if it still works properly though.

http://pastebin.com/vG8HKgmg

edit: and the compiled exe: http://upload.solidsurf.info/forums64.exe

The only real issue was MAXINT not being defined which I assumed to be INT_MAX

Colonel Taint fucked around with this message at 17:40 on May 13, 2012

Paolomania
Apr 26, 2006

Doctor Malaver posted:

OK, let's try!
http://pastebin.com/zFAVnBfD

This is highly portable C using standard libraries. You should be able to compile it for just about any platform, but when in Rome do as the Romans do.

1. Download and install the Windows SDK. This is a free-as-in-beer download that has a C compiler for Windows. Make sure you select the option to install Visual C.

2. Make a directory somewhere and put that old C file in it.

3. Open up a command shell (windows menu -> type "cmd" into the search box).

4. Inside the command shell, change to the Microsoft Visual C install directory. You will have to type something like "cd C:\Program Files\Microsoft Visual Studio 10.0\VC", but it could be in "Program Files (x86)" or something like that.

5. With the shell in this directory, type "vcvarsall.bat". This sets up the environment variables that the shell needs to compile a C program.

6. Change to the directory where you put the C file. Type "cl myprogram.c", (that is cee-ell in case your web font makes it look ambiguous) substituting the name of your .c file for myprogram.c.

7. Report back if an executable does not come out the other end.


edit: looks like a nice person did it for you!

Doctor Malaver
May 23, 2007

Ce qui s'est passé t'a rendu plus fort
It works! Many thanks!

Normally I would welcome the opportunity to learn something new but I just got out of the nightmare of building a PC DIY style so it's nice to get something effortlessly for a change.


edit: We still play Warcraft II :3

Doctor Malaver fucked around with this message at 22:25 on May 13, 2012

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
I have a file I/O assignment where we are forced to use the "open()" command to do some file manipulation. Specifically, we are supposed to copy a decimal integer from an input file and print it as a binary int to the output file. I'm not sure which header files are necessary for doing this, but I've included the following:

code:
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
This seems like a lot though, I'm not sure if I need all of these for simple file reading/writing.

For my file handling commands, I have the following:

code:
FILE *infile, *outfile;
infile = open(argv[1],O_RDONLY);
code:
outfile = open(argv[2],O_WRONLY,O_CREAT);
The goal is to open an input file for read-only, and an output file for write only that will create a new text file if none exists by the argument's name. Do I have to allocate system memory to the files? At the end, I am trying to free up the used memory with the "free()" command for both file pointers.

shrughes
Oct 11, 2008

(call/cc call/cc)

Harold Ramis Drugs posted:

I have a file I/O assignment where we are forced to use the "open()" command to do some file manipulation. Specifically, we are supposed to copy a decimal integer from an input file and print it as a binary int to the output file. I'm not sure which header files are necessary for doing this, but I've included the following:

Read the open(2) man page.

Harold Ramis Drugs posted:

code:
FILE *infile, *outfile;
infile = open(argv[1],O_RDONLY);
code:
outfile = open(argv[2],O_WRONLY,O_CREAT);

open doesn't return a FILE *. It returns an int. Read the man page.

Harold blah blah posted:

At the end, I am trying to free up the used memory with the "free()" command for both file pointers.

Never ever do this. FILE pointers (which are used with the C standard file API, not with the API you're trying to use) are just an abstract type. You need to fclose them, and fclose frees up the resources appropriately, unless it returns an error. You generally should not be freeing pointers that you did not allocate yourself, unless you're using a poorly designed library whose documentation says you must do exactly that.

shrughes fucked around with this message at 01:43 on May 16, 2012

Harold Ramis Drugs
Dec 6, 2010

by Y Kant Ozma Post
Allright, thanks. I changed my code to this, and it seems to work:

code:
int filedesc = open(argv[2], O_WRONLY | O_CREAT);
write(filedesc, ptr_end, strlen(ptr_end));
where ptr_end is a string.

Also, I need to set up this program to display error messages if there is any I/O problems. Is there any way I could tell if there was an I/O error with either of these commands?

Blotto Skorzany
Nov 7, 2008

He's a PSoC, loose and runnin'
came the whisper from each lip
And he's here to do some business with
the bad ADC on his chip
bad ADC on his chiiiiip

Harold Ramis Drugs posted:

Allright, thanks. I changed my code to this, and it seems to work:

code:
int filedesc = open(argv[2], O_WRONLY | O_CREAT);
write(filedesc, ptr_end, strlen(ptr_end));
where ptr_end is a string.

Also, I need to set up this program to display error messages if there is any I/O problems. Is there any way I could tell if there was an I/O error with either of these commands?

The 'return value' and 'errors' sections of the manpages for open(2) and write(2) say it pretty well :)

You seem to be a bit unfamiliar with C and Unix, so I'll quote some of the manpage for write(2) here:

quote:

Return Value
On success, the number of bytes written is returned (zero indicates nothing was written). On error, -1 is returned, and errno is set appropriately.

If count is zero and fd refers to a regular file, then write() may return a failure status if one of the errors below is detected. If no errors are detected, 0 will be returned without causing any other effect. If count is zero and fd refers to a file other than a regular file, the results are not specified.
Errors
EAGAIN
The file descriptor fd refers to a file other than a socket and has been marked nonblocking (O_NONBLOCK), and the write would block.
EAGAIN or EWOULDBLOCK
The file descriptor fd refers to a socket and has been marked nonblocking (O_NONBLOCK), and the write would block. POSIX.1-2001 allows either error to be returned for this case, and does not require these constants to have the same value, so a portable application should check for both possibilities.
EBADF
fd is not a valid file descriptor or is not open for writing.
EDESTADDRREQ
fd refers to a datagram socket for which a peer address has not been set using connect(2).
EFAULT
buf is outside your accessible address space.
EFBIG
An attempt was made to write a file that exceeds the implementation-defined maximum file size or the process's file size limit, or to write at a position past the maximum allowed offset.
EINTR
The call was interrupted by a signal before any data was written; see signal(7).
EINVAL
fd is attached to an object which is unsuitable for writing; or the file was opened with the O_DIRECT flag, and either the address specified in buf, the value specified in count, or the current file offset is not suitably aligned.
EIO
A low-level I/O error occurred while modifying the inode.
ENOSPC
The device containing the file referred to by fd has no room for the data.
EPIPE
fd is connected to a pipe or socket whose reading end is closed. When this happens the writing process will also receive a SIGPIPE signal. (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.)

Other errors may occur, depending on the object connected to fd.

Nb. that the way you would find this is by running man 2 write, if you're unfamiliar with the invocation of the man program. The 2 there denotes the section of the manual to look in; typically you will see functions and programs with manual pages written with the section in parens as I did above, eg. write(2). This is often optional, but for some things like printf where there is both a stdlib function (documented in section 3) and a command line program (documented in section 1) with the same name it is needed to disambiguate.

The layout of the manual sections is typically thus:
code:
1	General commands
2	System calls
3	Library functions, covering in particular the C standard library
4	Special files (usually devices, those found in /dev) and drivers
5	File formats and conventions
6	Games and screensavers
7	Miscellanea
8	System administration commands and daemons

Blotto Skorzany fucked around with this message at 06:16 on May 16, 2012

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I also want to point out that errno is a global. You will need to #include <errno.h> if you want to use it, and if you want to use the error declarations.

shrughes
Oct 11, 2008

(call/cc call/cc)

Suspicious Dish posted:

I also want to point out that errno is a global. You will need to #include <errno.h> if you want to use it, and if you want to use the error declarations.

Actually it's thread-local.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!
If you'd prefer a web-based reference then this one's pretty good:
http://www.cplusplus.com/reference/clibrary/

pseudorandom name
May 6, 2007

Not good enough to document the functions that Harold Ramis Drugs' homework requires.

Adbot
ADBOT LOVES YOU

shrughes
Oct 11, 2008

(call/cc call/cc)
Yeah that is not a POSIX reference.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply