Amiga.org
		Operating System Specific Discussions => Amiga OS => Amiga OS -- Development => Topic started by: Marcb on May 21, 2009, 01:39:21 PM
		
			
			- 
				I'm putting together a small app that reads paths entered line by line in a text file.
 
 I know the issue with reading a variable length line using Fgets and the newline character is as old as the hills but I was wondering if anyone has a more elegant way of dealing with the newline character than my method? :
 
 Fgets(buf,sizeof(buf),*file);
 buf[strlen(buf)-1]='\0';
 
 It works but I always think it's too messy and that there must be a better way...
- 
				That's not bad, but to be complete you should also check for DOS line endings (\r\n) in case those files are edited in a Windows machine.
			
- 
				That's a good point, these days it would be very likely the file would be edited on a Windows machine, thanks for the tip !
			
- 
				I'm putting together a small app that reads paths entered line by line in a text file.
 
 I know the issue with reading a variable length line using Fgets and the newline character is as old as the hills but I was wondering if anyone has a more elegant way of dealing with the newline character than my method? :
 
 Fgets(buf,sizeof(buf),*file);
 buf[strlen(buf)-1]='\0';
 
 It works but I always think it's too messy and that there must be a better way...
 
 One way to handle it is to use sscanf:
 #include <stdio.h>
 
 int main(void)
 {
 char tmp[80], buf[80];
 while (fgets(tmp, sizeof(tmp), stdin))
 {
 if (sscanf(tmp, "%[^\r\n]", buf) != 1)
 {
 buf[0] = '\0';
 }
 printf("%s\n", buf);
 }
 return 0;
 }
- 
				That's not bad, but to be complete you should also check for DOS line endings (\r\n) in case those files are edited in a Windows machine. 
 As far as I know all libc implementations on windoze do automagic \r\n -> \n translation when reading file opened in 'text' mode (that is no "b" is appended to the fopen mode. stdin/stdout/stderr are in this mode, too). Also, when writing to filehandle that is in 'text' mode single \n again is translated to \r\n.
 
 Checking for \r doesn't hurt, however.
- 
				It should also be noted that the value of '\n' is entirely library-dependent, and '\n' can and should be converted to an environment-specific newline sequence by the library. Technically, a text stream written on system A can't be safely read on system B until a low-level line ending conversion has taken place. Thankfully, the conversion is typically 0x0D0A <-> 0x0A, but you can't take it for granted, particularly when you know the text stream was created on a non-ASCII source system.
 
 As noted, '\n' in the C standard library translates to CR+LF in the text stream in DOS/Windows and LF in AmigaDOS.
 
 EDIT: If you're looking to do strict ASCII conversion or scanning, then "\x0d\x0a" for "\r\n" and "\x0a" for "\n" might be "safer."
 
 Wikipedia's Newline article covers this in pretty good detail.