Thread: help me with this memory mapped file code

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    5

    Thumbs up help me with this memory mapped file code

    hello everybody,

    I am new to this forum..I am trying to run a code..
    I created a text file first with the name mmap.txt and wrote some lines in that....but I dont know why its not working...I just used simple printf() scanf() functions.... It reads integer value for the position three times...but doesnt reads a character....can somebody please help me with that?
    the code is:
    Code:
    #include<unistd.h>
    #include<sys/mman.h>
    #include<sys/types.h>
    #include<fcntl.h>
    #include<stdio.h>
    #include<string.h>
    
    int main()
    {
       int fd; 
       char *fileptr; 
       int i;
       int x;
       char ch;
       fd=open("mmap.txt",O_RDWR);
       fileptr=mmap(0,26,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
       for(i=0;i<3;i++)
       {
          printf("Enter the position in the file you want to change: ");
          scanf("%d",&x);
          printf("\n");
          printf("Enter the new letter for that position: ");
          scanf("%c",&ch);
          printf("\n");
          fileptr[x-1]=ch;
          printf("\n");
       }
      munmap(fileptr,26);
      close(fd);
      return 1;
      }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    You type in
    42\n

    scanf &#37;d will read the 42
    scanf %c will read the \n

    An easy fix would be to use %s with a char array, then use the first character.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    5
    Thanks a lot Salem!!! thats working now.I appreciate your help.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. Batch file programming
    By year2038bug in forum Tech Board
    Replies: 10
    Last Post: 09-05-2005, 03:30 PM
  4. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM