Hi i want to write numbers from 0 to 255 to fd, can someone pls correct the errors in the below file? Thanks in advance
Code: Actually need to increse / decrese the brightness of an led connected to a particular port. so i need to write these numbers to the specified file called brightness.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
void main(void)
{
int fd, t;
char buf[300];
char z;
while(1)
{
fd = open("/sys/class/leds/pwmD0/brightness", O_WRONLY);
if (fd < 0)
{
abort();
}
for(t=0;t<10000000;t++); //random sw delay
for(z=0;z<255;z++)
{
write(fd, "%s", strlen(z));
printf("Received: %s\n",buf[z]);
}
for(t=0;t<10000000;t++);
for(z=255;z>0;z--)
{
write(fd, "%s", strlen(z));
printf("Received: %s\n",buf[z]);
}
close(fd);
}
}
This:
write(fd, "%s", strlen(z));
makes no sense, the write() function is not printf(). Read more documentation.
You need something like:
char buf[32];
const size_t len = snprintf(buf, sizeof buf, "%d\n", z);
write(fd, buf, len);
Related
This program is meant to take as parameter a file, then read a string from standard input and write its length into the file, then read the content of the file (which is supposed to contain the lengths of the strings from the standard input) and write it in standard output:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX_BUFF 4096
int main(int argc, char **argv)
{
if (argc != 2)
{
puts("you must specify a file!");
return -1;
}
int nRead;
char buffer[MAX_BUFF], tmp;
int fd;
puts("write \"end\" to stop:");
fd = open(argv[1], O_RDWR | O_CREAT | O_APPEND, S_IRWXU);
while ((nRead = read(STDIN_FILENO, buffer, MAX_BUFF)) > 0 && strncmp(buffer,"end", nRead-1) != 0 )
{
if ( write(fd, &nRead, 1) < 0 )
{
perror("write error.");
return -1;
}
}
puts("now i am gonna print the length of the strings:");
lseek(fd, 0, SEEK_SET); //set the offset at start of the file
while ((nRead = read(fd, buffer, 1)) > 0)
{
tmp = (char)buffer[0];
write(STDOUT_FILENO, &tmp, 1);
}
close(fd);
return 0;
}
this is the result:
write "end" to stop:
hello
world
i am a script
end
now i am gonna print the length of the strings:
I tried to convert the values written in the file into char before write in standard output with no success.
How am i supposed to print on standard output the lengths by using unbuffered I/O? Thank you for your replies
EDIT: i changed the read from file with this:
while((read(fd, &buffer, 1)) > 0)
{
tmp = (int)*buffer;
sprintf(buffer,"%d:", tmp);
read(fd, &buffer[strlen(buffer)], tmp);
write(STDOUT_FILENO, buffer, strlen(buffer));
}
but actually i have no control on the effective strlen of the string thus the output is this:
13:ciao atottti
4:wow
o atottti
5:fine
atottti
as you can see, the strlength is correct because it consinder the newline character ttoo. Still there is no control on the effective buffer size.
So I want to make a file named genData.c that when executed for example: ./genData filename.txt will write 1 character to that file 1000 times.
In essence creating a 1kb file.
I would like to be able to modify the for loop, say 100000 times, to generate a 1MB file and so on.
Here is what I have tried and it compiles but when executed causes a segmentation fault.
Any suggestions? Sorry C is a language I've never dabbled in.
#include <stdio.h>
int main (int argc, char *argv) {
char ch = 'A';
FILE *fp;
fp = fopen(argv[1], "wb");
int i;
for (i = 0; i < 1000; i++) {
fwrite(&ch, sizeof(char), 1, fp);
}
fclose(fp);
return 0;
}
If you compile with warnings, you get a hint as to the exact problem:
test.c:3:5: warning: second argument of ‘main’ should be ‘char **’ [-Wmain]
int main (int argc, char *argv) {
^
All your troubles start downstream of this error. Fix this argument, and your code will work.
In the future, get into the habit of compiling with warnings turned on:
$ gcc -Wall foo.c
...
This will help catch typos and other oddities that will cause problems.
Since you tagged it Linux, this is how you can do it with the system-level functions (this should be a correct, most efficient way to do it):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sysexits.h>
#include <fcntl.h>
#include <string.h>
ssize_t /* Write "n" bytes to a descriptor */
writen(int fd, const void *ptr, size_t n);
int
main (int argc, char** argv) {
char buf[1000];
memset(buf, 'A', sizeof(buf));
int fd;
if((fd = open(argv[1], O_WRONLY|O_CREAT, 0666))<0){
perror(argv[1]);
exit(EX_NOPERM);
}
ssize_t left = writen(fd, buf, sizeof(buf));
if(left)
perror("write error\n");
return !!left;
}
ssize_t /* Write "n" bytes to a descriptor */
writen(int fd, const void *ptr, size_t n) {
size_t nleft;
ssize_t nwritten;
nleft = n;
while (nleft > 0) {
if ((nwritten = write(fd, ptr, nleft)) < 0) {
if (nleft == n)
return(-1); /* error, return -1 */
else
break; /* error, return amount written so far */
} else if (nwritten == 0) {
break;
}
nleft -= nwritten;
ptr += nwritten;
}
return(n - nleft); /* return >= 0 */
}
#include <stdio.h>
#include <stdlib.h>
#define SIZE_OF_FILE 1024
int main(int argc, char *argv[])
{
FILE *fdest;
char ch = '\n';
if(argc != 2)
exit(EXIT_FAILURE);
fdest = fopen(argv[1], "wb");
if (fdest == NULL)
exit(EXIT_FAILURE);
fseek(fdest, SIZE_OF_FILE - 1, SEEK_CUR);
fwrite(&ch, sizeof(char), 1, fdest);
fclose(fdest);
return 0;
}
In essence creating a 1kb file
if the only purpose is creating a file with sizeof x, it is more simple i belive.
So I'm using mmap to then write to another file. But the weird thing is, when my code hits mmap, what it does is clears the file. So I have a file that's populated with random characters (AB, HAA, JAK, etc...). What it's supposed to do is use mmap as read basically and then write that file to the new file. So that first if (argc == 3) is the normal read and write, the second if (argc ==4) is supposed to use mmap. Does anyone have any idea why on Earth this is happening?
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/resource.h>
int main(int argc, char const *argv[])
{
int nbyte = 512;
char buffer[nbyte];
unsigned char *f;
int bytesRead = 0;
int size;
int totalBuffer;
struct stat s;
const char * file_name = argv[1];
int fd = open (argv[1], O_RDONLY);
int i = 0;
char c;
int fileInput = open(argv[1], O_RDONLY);
int fileOutPut = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
fstat(fileInput, &s);
size = s.st_size;
printf("%d\n", size);
if (argc == 3)
{
printf("size: %d\n", size);
printf("nbyte: %d\n", nbyte);
while (size - bytesRead >= nbyte)
{
read(fileInput, buffer, nbyte);
bytesRead += nbyte;
write(fileOutPut, buffer, nbyte);
}
read(fileInput, buffer, size - bytesRead);
write(fileOutPut, buffer, size - bytesRead);
}
else if (argc == 4)
{
int i = 0;
printf("4 arg\n");
f = (char *) mmap (0, size, PROT_READ, MAP_PRIVATE, fileInput, 0);
/* This is where it is being wipped */
}
close(fileInput);
close(fileOutPut);
int who = RUSAGE_SELF;
struct rusage usage;
int ret;
/* Get the status of the file and print some. Easy to do what "ls" does with fstat system call... */
int status = fstat (fd, & s);
printf("File Size: %d bytes\n",s.st_size);
printf("Number of Links: %d\n",s.st_nlink);
return 0;
}
EDIT: I wanted to mention that the first read and write works perfectly, it is only when you try to do it through the mmap.
If you mean it's clearing your destination file, then yes, that's exactly what your code will do.
It opens the destination with truncation and then, in your argc==4 section, you map the input file but do absolutely nothing to transfer the data to the output file.
You'll need a while loop of some description, similar to the one in the argc==3 case, but which writes the bytes in mapped memory to the fileOutput descriptor.
code:
#include <fcntl.h>
#include <linux/fs.h>
#include <stdio.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/time.h>
void write_zero(char * file, unsigned long bytes)
{
printf("Zeroing %s\n", file);
unsigned int wrote = 0, total = 0;
int fd, i, buf;
char obj = 0x00;
fd = open(file, O_RDWR, DEFFILEMODE);
lseek(fd, 0, SEEK_SET);
write(fd, &obj, bytes);
}
int main(int argc, char * * argv)
{
int fd;
unsigned long blocks = 0;
char check = 0x0;
fd = open(argv[1], O_RDONLY);
ioctl(fd, BLKGETSIZE, &blocks);
close(fd);
printf("Blocks: %lu\tBytes: %lu\tGB: %.2f\n",
blocks, blocks * 512, (double)blocks * 512.0 / (1024 * 1024 * 1024));
do
{
printf("Write 0x0 to %s? [y/N] ", argv[1]);
fflush(stdout);
}
while (scanf("%c", &check) < 1);
if (check == 'y')
{
write_zero(argv[1], blocks * 512);
}
}
I get nothing actually written to the device.. I copied my open line from the 'dd' source code, thinking maybe it was not opened right. dd can zero the device, but this program does not. Any ideas?
It seems like this has been beaten to death but
char obj = 0x00;
fd = open(file, O_RDWR, DEFFILEMODE);
lseek(fd, 0, SEEK_SET);
write(fd, &obj, bytes);
Is not going to write zeros. It's going to write garbage from the stack.
gcc 4.4.1
I am using the read function to read in a wave file. However, when it gets to the read function. Execution seems to stop and freezes. I am wondering if I am doing anything wrong with this.
The file size test-short.wave is: 514K.
What I am aiming for is to read the file into the memory buffer chunks at a time. Currently I just testing this.
Many thanks for any suggestions,
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
char buff = malloc(10240);
int32_t fd = 0;
int32_t bytes_read = 0;
char *filename = "test-short.wav";
/* open wave file */
if((fd = (open(filename, O_RDWR)) == -1))
{
fprintf(stderr, "open [ %s ]\n", strerror(errno));
return 1;
}
printf("Opened file [ %s ]\n", filename);
printf("sizeof(buff) [ %d ]\n", sizeof(buff));
bytes_read = read(fd, buff, sizeof(buff));
printf("Bytes read [ %d ]\n", bytes_read);
return 0;
}
=== Edit Corrections ===
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
char buff[10240] = {0};
int32_t fd = 0;
int32_t bytes_read = 0;
const char *filename = "test-short.wav";
fd = open(filename, O_RDWR);
if(fd == -1)
{
fprintf(stderr, "open [ %s ]\n", strerror(errno));
return 1;
}
printf("sizeof(buff) [ %d ]\n", sizeof(buff));
printf("strlen(buff) [ %d ]\n", strlen(buff));
bytes_read = read(fd, buff, sizeof(buff));
printf("Bytes read [ %d ]\n", bytes_read);
return 0;
}
You assign pointer to the char, not char*.
You read sizeof(char) (likely 1 byte), not 10240.
You read the data into whatever buff, converted to pointer, points to, not into buff.
The precedence issue mentioned by Ignacio Vazquez-Abrams is still relevant.
You call strlen() on char, which doesn't make much sense. Even less before populating what is supposed to be buffer.
You assign const char * (string literal) to char*.
Aren't compiler warnings swarming around this code?
== has higher precedence than =:
if((fd = open(filename, O_RDWR)) == -1)