Learning to program in C. Used a textbook to learn about writing data randomly to a random access file. It seems like the textbook code works ok. However the output in the Notepad file is: Jones Errol Ÿru ”#e©A Jones Raphael Ÿru €€“Ü´A. This can't be correct yeah? Do you know why the numbers don't show?
I have no idea how to format code properly. Always someone tells me it is bad. I use CTRL +K. And in my compiler follow the book exactly. I'm sorry if it isn't correct. Maybe you can tell me how? Thanks
Here is the code:
#include <stdio.h>
//clientData structure definition
struct clientData{
int acctNum;
char lastName[15];
char firstName[10];
double balance;
};
int main (void){
FILE *cfPtr;//credit.dat file pointer
//create clientData with default information
struct clientData client={0,"","",0.0};
if ((cfPtr=fopen("c:\\Users\\raphaeljones\\Desktop\\clients4.dat","rb+"))==NULL){
printf("The file could not be opened\n");
}
else {
//require user to specify account number
printf("Enter account number"
"(1 to 100, 0 to end input)\n");
scanf("%d",&client.acctNum);
// users enters information which is copied into file
while (client.acctNum!=0) {
//user enters lastname,firstname and balance
printf("Enter lastname,firstname, balance\n");
//set record lastName,firstname and balance value
fscanf(stdin,"%s%s%lf", client.lastName,
client.firstName, &client.balance);
//seek position in file to user specified record
fseek(cfPtr,
(client.acctNum-1)* sizeof (struct clientData),
SEEK_SET);
//write user specified information in file
fwrite(&client,sizeof(struct clientData),1,cfPtr);
//enable user to input another account number
printf("Enter account number\n");
scanf("%d",&client.acctNum);
}
fclose(cfPtr);
return 0;
}
You have created a structure clientData which contains an integer, two strings and a double. You open the file in binary mode and you use fwrite() to write the structure to it.
This means you are writing the integer and the double in binary, and not as character strings, so what you see is logically correct, and you could read the file back into a structure with fread() and then print it out.
If you want to create a text file, you should use fprintf(). You can specify the field widths for integer and double values, so you can create a fixed-length record (which is essential for random access).
Related
How to export CANoe trace data in an excel file(.csv or.xlsx) where we can see the messages and signals' names along with their updated values.
I tried storing the log file in .csv format but couldn't see the message and signal name details and their value. I hope there is someway to store the CANoe trace data in an excel file format which can be readable. Any suggestions? Any answer is highly appreciated.
You can use the Logging/Export Block to save the entire measurement in a file as BLF or ASCII. Afterwards you convert the BLF into other formats like CSV or MAT. This can be found under Tools->Convert (I don't know the correct menu items in english, because I have only the german version of CANoe). If you convert an BLF file, you can select the time and the signals you want.
Another solution is to write an own exporter in CAPL and write directly into a file (I didn't try the code, it's just an idea).
on Start {
glbHandle = OpenFileWrite ("Data.csv", 2);
}
on message * {
int i;
char buffer [64];
write("[%07.3f] %03X,", this.time / 100000.0, this.id);
for (i = 0; i < this.dlc; i++) {
snprintf(buffer, elcount(buffer), "%02X, ", this.byte(i));
filePutString(buffer, elcount(buffer), glbHandle);
}
on StopMeasurement {
fileClose (glbHandle);
}
i would like to ask, how i can send data via usart as integer, i mean variable which stores number. I am able to send char variable, but terminal shows me ascii presentation of this number and i need to see number.
I edited code like shown below but it gives me error: "conflicting types for 'USART_Transmit'"
#include <avr/io.h>
#include <util/delay.h>
#define FOSC 8000000// Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
void USART_Init( unsigned int ubrr );
void USART_Transmit( unsigned char data );
unsigned char USART_Receive( void );
int main( void )
{
unsigned char str[5] = "serus";
unsigned char strLenght = 5;
unsigned int i = 47;
USART_Init ( MYUBRR );
//USART_Transmit('S' );
while(1)
{
/*USART_Transmit( str[i++] );
if(i >= strLenght)
i = 0;*/
USART_Transmit(i);
_delay_ms(250);
}
return(0);
}
void USART_Init( unsigned int ubrr )
{
/* Set baud rate */
UBRR0H = (unsigned char)(ubrr>>8);
UBRR0L = (unsigned char)ubrr;
/* Enable receiver and transmitter */
UCSR0B = (1<<RXEN)|(1<<TXEN);
/* Set frame format: 8data, 2stop bit */
UCSR0C = (1<<USBS)|(3<<UCSZ0);
}
void USART_Transmit( unsigned int data )
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<<UDRE)) )
;
/* Put data into buffer, sends the data */
UDR0 = data;
}
unsigned char USART_Receive( void )
{
/* Wait for data to be received */
while ( !(UCSR0A & (1<<RXC)) )
;
/* Get and return received data from buffer */
return UDR0;
}
Do you have any ideas what is wrong?
PS: I hope you understand what im trying to explain.
I like to use sprintf to format numbers for serial.
At the top of your file, put:
#include <stdio.h>
Then write some code in a function like this:
char buffer[16];
sprintf(buffer, "%d\n", number);
char * p = buffer;
while (*p) { USART_Transmit(*p++); }
The first two lines construct a null-terminated string in the buffer. The last two lines are a simple loop to send all the characters in the buffer. I put a newline in the format string to make it easier to see where one number ends and the other begins.
Technically a UART serial connection is just a stream of bits divided into symbols of a certain length. It's perfectly possible send the data in raw form, but this comes with a number of issues the must be addressed:
How to identify the start and end of a transmission unambiguously?
How to deal with endianess on either side of the connection?
How to serialize and deserialize the data in a robust way?
How to deal with transmission errors?
At the end of the day it turns out, that you never can resolve all the ambiguties and binary data somehow must be escaped or otherwise encoded to prevent misinterpretation.
As far as delimiting transmissions is concerned, that has been addressed by the creators of the ASCII standard through the set of nonprintable control characters: Of interest for you should be the special control characters
STX / 0x02 / Start of Text
ETX / 0x03 / End of Text
There are also other control characters which form a pretty complete set to make up data structures; you don't need JSON or XML for this. However ASCII itself does support the transmission of arbitrary binary data. However the standard staple for this task for a long time has been and is base64 encoding. Use that for transmission of arbitrary binary data.
Numbers you probably should not transmit in binary at all; just push digits around; if you're using octal or hexadecimal digits parsing into integers is super simple (boils down to a bunch of bit masking and shifting).
For example I have a list of some items in a text file. I want to read that data one by one. How can I do that in Swift? I've found NSString.stringWithContentsOfFile(path) but this reads whole file. In C++ i was using ifstream for that. Example:
ifstream fd(fileName);
string code, type, title;
int price, date;
getline(fd, title);
while (!fd.eof()) {
getline(fd, code, ',');
fd >> ws;
getline(fd, type, ',');
fd >> ws;
fd >> date;
fd.ignore();
fd >> price;
fd.ignore();
}
fd.close();
And sample text file for that:
Title of List
K123, document, 1994, 12500
S156, photo, 2006, 7000
R421, book, 1998, 6000
How can I read files with Swift like that and get words in it one by one?
Is it appropriate for you to read the whole file and then just parse the string into an array of characters/words? If so, consider using
func componentsSeparatedByString(_ separator: String) -> [AnyObject]
If you know there is a space or comma or whatever separator in between each token, this could be a possible solution. If that's not acceptable just comment below.
Instead of:
stringstream szBuffer;
szBuffer>>string;
myFunc(string);
How do I do like:
muFunc(szBuffer.NextString());
I dont want to create a temp var just for passing it to a function.
If you want to read the whole string in:
// .str() returns a string with the contents of szBuffer
muFunc(szBuffer.str());
// Once you've taken the string out, clear it
szBuffer.str("");
If you want to extract the next line (up to the next \n character), use istream::getline:
// There are better ways to do this, but for the purposes of this
// demonstration we'll assume the lines aren't longer than 255 bytes
char buf[ 256 ];
szBuffer.getline(buf, sizeof(buf));
muFunc(buf);
getline() can also take in a delimiter as a second parameter (\n by default), so you can read it word by word.
I am working on a C code to read in three columns of numbers from an input file and then do basic math with the numbers obtained. My input file looks like:
155.4996 38.0078 7.65
93.9968 44.9926 7.68
I am currently trying to separate columns using sscanf. To get this started I am trying to read in the columns and print just the third column to an output file. Below is what I have right now:
FILE * fp;
FILE * fp2;
char *string;
char out[2000];
char read[1000];
int column1, column2, column3;
strcpy(read, "casecent");
strcpy(out, "Diff");
fp = fopen(read, "r");
fp2 = fopen(out, "w+");
while (!feof(fp))
{
fgets(string, 1000, fp);
sscanf(string, "%d %d %d", &column1, &column2, &column3);
fprintf(fp2,"%d\n", column3);
}
I am currently getting zeros in the output file instead of numbers. I'm sure I'm just missing something small and dumb but if you could help me out it would be much appreciated.
Use float or double for the column variables' data types. Then use %f or %lf respectively in the format string for sscanf, depending on which data type you chose.
If you want to store or print the values as integers, you'll still have to read them as floats or doubles first, then convert.